其他分享
首页 > 其他分享> > CodeGo.net>如何在ServiceStack.OrmLite中使用OnUpdate =“ CASCADE”

CodeGo.net>如何在ServiceStack.OrmLite中使用OnUpdate =“ CASCADE”

作者:互联网

我试图了解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),将其保存,然后查看子对象的值.该值必须匹配.

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

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

[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.
    }
}

标签:orm,foreign-keys,ormlite-servicestack,attributes,c
来源: https://codeday.me/bug/20191122/2059662.html