gpt4 book ai didi

c# - 与 TPT 代码优先 Entity Framework 中的引用约束冲突

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:47 26 4
gpt4 key购买 nike

我在 Entity Framework 6 中使用 TPT 代码优先并具有以下设置:

public abstract class Product
{
[Key]
public string ProductID { get; set; }
// a bunch of trivial properties like dates and floats
}

[Table("SpecialProducts")]
public class SpecialProduct : Product
{
// more trivial properties
public List<Property> MyProperties { get; set; }
}

public class Property
{
[Key]
public int ID { get; set; }
[Required]
public SpecialProduct Product { get; set; }
// property data
}

public class MyDbContext : DbContext
{
public DbSet<Product> AllProducts { get; set; }

public MyDbContext()
: base("MyDataBase")
{}

public RemoveSomeProducts()
{
var products = from product in AllProducts where /* some condition */ select product;
AllProducts.RemoveRange(products);
SaveChanges();
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// I know I don't need both statements, and my guess is I need the first, but at this point I don't know anything anymore
modelBuilder.Entity<Property>()
.HasRequired(property => property.Product)
.WithMany(product => product.MyProperties)
.WillCascadeOnDelete(true);

modelBuilder.Entity<SpecialProduct>()
.HasMany(product => product.MyProperties)
.WithRequired(property => property.Product)
.WillCascadeOnDelete(true);
}

}

调用 RemoveSomeProducts() 时出现以下异常:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Properties_dbo.SpecialProducts_Product_ProductID". The conflict occurred in database "MyDataBase", table "dbo.Properties", column 'Product_ProductID'.

对我来说,这听起来像是属于已删除 SpecialProductsProperties 没有被删除。我对数据库没有什么经验,但根据我的理解,这应该使用级联删除来修复,但我似乎无法配置它。

所以我的问题显然是:我该如何解决这个问题?

对我的情况似乎没有帮助但可能对其他人有用的潜在重复项:

EF6 Cascade Delete

Code First Cascade Delete

TPT Cascade Delete

最佳答案

首先,您必须在查询中明确包含您的导航属性。由于某些原因,RemoveRange 无法按预期使用级联删除,但如果您逐个迭代并删除它,它就可以工作。

var products = Set<SpecialProduct>().Include(p => p.MyProperties).ToList();
products.ForEach(p => AllProducts.Remove(p));
SaveChanges();

关于c# - 与 TPT 代码优先 Entity Framework 中的引用约束冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51855433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com