C# 实体框架导航集合属性删除
我有以下两个实体:C# 实体框架导航集合属性删除,c#,entity-framework-6,C#,Entity Framework 6,我有以下两个实体: public class FirstEntity { public int Id { get; set; } public ICollection<SecondEntity> SecondEntityCollection { get; set; } } public class SecondEntity { [Key] [Column(Order = 0)] public int FirstEntitySomeId {
public class FirstEntity
{
public int Id { get; set; }
public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}
public class SecondEntity
{
[Key]
[Column(Order = 0)]
public int FirstEntitySomeId { get; set; }
[Key]
[Column(Order = 1)]
public int SecondEntityId { get; set; }
}
var firstEntity=this.context.FirstEntities.Where(x=>x.Id==someId);
firstEntity.SecondEntityCollection.Clear();
this.context.FirstEntities.Remove(firstEntity);
this.context.SaveChanges();
删除FirstEntity
对象时,我会执行以下操作:
public class FirstEntity
{
public int Id { get; set; }
public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}
public class SecondEntity
{
[Key]
[Column(Order = 0)]
public int FirstEntitySomeId { get; set; }
[Key]
[Column(Order = 1)]
public int SecondEntityId { get; set; }
}
var firstEntity=this.context.FirstEntities.Where(x=>x.Id==someId);
firstEntity.SecondEntityCollection.Clear();
this.context.FirstEntities.Remove(firstEntity);
this.context.SaveChanges();
但是,我仍然得到以下例外情况:
DELETE语句与引用约束“…”冲突。冲突发生在数据库“database”、表“dbo.SecondEntity”、列“FirstEntitySomeId”中
如何在删除firstEntity
对象之前正确清除集合
值得一提的是,我正在努力避免级联删除。我确实想删除数据库中的孤立项。但是,如果最佳解决方案/实践是使用级联删除,我将使用它
这可能吗?您可以按如下所示进行尝试
var firstEntity=this.context.FirstEntities
.Where(x=>x.Id==someId)
.Include(s => s.SecondEntityCollection);
this.context.FirstEntities.Remove(firstEntity);
foreach (var s in firstEntity.SecondEntityCollection.ToList())
{
this.context.SecondEntityCollection.Remove(s);
}
this.context.SaveChanges();
我试图避免级联删除
:这是否意味着您需要在数据库中保留孤立数据?否,我还想删除集合中的子项。我现在只是尽量避免使用WillCascadeOnDelete()
。但是,如果这是最佳选项,我将使用它。firstEntity.SecondEntityCollection.Count()
为0,这意味着没有删除SecondEntity
子项。我找不出为什么SecondEntityCollection
是空的。对不起,我没有得到你提到的内容?这是有效的还是有什么问题?对不起,我不太清楚firstEntity.SecondEntityCollection.ToList()
返回一个空集合-因此不会发生删除操作,因为SecondEntityCollection
中没有任何项目。非常感谢您的帮助:)