我试图了解OnUpdate =“ CASCADE”参数的作用以及如何使用它。

在ForeignKeyAttributeTests(ServiceStack.OrmLite on Github)中,Test CascadesOnDelete非常清楚:

    [Test]
    public void CascadesOnDelete()
    {
        using (var dbConn = ConnectionString.OpenDbConnection())
        {
            dbConn.CreateTable<TypeWithOnDeleteCascade>(true);

            dbConn.Save(new ReferencedType { Id = 1 });
            dbConn.Save(new TypeWithOnDeleteCascade { RefId = 1 });

            Assert.AreEqual(1, dbConn.Select<ReferencedType>().Count);
            Assert.AreEqual(1, dbConn.Select<TypeWithOnDeleteCascade>().Count);

            dbConn.Delete<ReferencedType>(r => r.Id == 1);

            Assert.AreEqual(0, dbConn.Select<ReferencedType>().Count);
            Assert.AreEqual(0, dbConn.Select<TypeWithOnDeleteCascade>().Count);
        }
    }


但是没有测试可以查看OnUpdate的工作方式以及如何级联更新,您能否通过显示OnUpdate =“ CASCADE”的小型单元测试来帮助我?

这是测试中使用的类型:

public class ReferencedType
{
    public int Id { get; set; }
}


public class TypeWithSimpleForeignKey
{
    [AutoIncrement]
    public int Id { get; set; }
    [References(typeof(ReferencedType))]
    public int RefId { get; set; }
}

public class TypeWithOnDeleteCascade
{
    [AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(ReferencedType), OnDelete = "CASCADE")]
    public int? RefId { get; set; }
}

public class TypeWithOnDeleteAndUpdateCascade
{
    [AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(ReferencedType), OnDelete = "CASCADE", OnUpdate = "CASCADE")]
    public int? RefId { get; set; }
}

最佳答案

对Update的CASCADE操作只是更新Child对象中的引用。为了能够看到结果,您需要更改父对象上的引用(对象ID),将其保存,然后查看子对象的值。该值必须匹配。

换句话说,使用您的示例:更新Id对象的ReferencedType属性应更新引用它的所有RefId对象的TypeWithOnDeleteAndUpdateCascade属性。

我认为以下测试用例可以回答您的问题:

[Test]
public void CascadesOnUpdate()
{
    using (var dbConn = ConnectionString.OpenDbConnection())
    {
        dbConn.CreateTable<TypeWithOnDeleteAndUpdateCascade>(true);

        dbConn.Save(new ReferencedType { Id = 1 });
        dbConn.Save(new TypeWithOnDeleteAndUpdateCascade { Id = 1, RefId = 1 });

        Assert.AreEqual(1, dbConn.Select<ReferencedType>().Count);
        Assert.AreEqual(1, dbConn.Select<TypeWithOnDeleteAndUpdateCascade>().Count);

        dbConn.Update<ReferencedType>(new { Id = "2" }, p => p.Id== "1");

        TypeWithOnDeleteAndUpdateCascade obj = db.Single<TypeWithOnDeleteAndUpdateCascade>("Id = 1")

        Assert.AreEqual(obj.RefId, 2);
        // making sure that the RefId got updated, because of the cascade.
    }
}

关于c# - 如何在ServiceStack.OrmLite中使用OnUpdate =“CASCADE”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20312175/

10-10 03:21