我试图了解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; }
}
答案 0 :(得分:3)
Update上的CASCADE
操作只是更新Child对象中的引用。为了能够查看结果,您需要更改Parent对象上的引用(对象ID),保存它,然后查看Child对象的值。该值必须匹配。
换句话说,使用您的示例:更新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.
}
}