我正在尝试从数据库中删除一个Group对象(由EF CodeFirst创建),当集合Items为空时它可以正常工作。如果它不是空的,我有DbUpdateException。这段代码出了什么问题?
public class Group
{
public int Id {get;set;}
[ForeignKey("OptionalParent")]
public int? OptionalParentId { get; set; }
public OptionalParent OptionalParent { get; set; }
[ForeignKey("RequiredParent")]
public int RequiredParentId { get; set; }
[Required]
public RequiredParent RequiredParent { get; set; }
List<Item> items = null;
public List<Item> Items // works fine only when this list is empty
{
get
{
return items;
}
set
{
items = value;
OnPropertyChanged("Items");
}
}
}
public class Item
{
public int Id {get;set;}
[ForeignKey("Group")]
public int? GroupId { get; set; }
public Group Group{ get; set; }
[ForeignKey("RequiredParent")] // might be the same entity as Group's RequiredParent
public int RequiredParentId { get; set; }
[Required]
public RequiredParent RequiredParent{ get; set; }
}
我正在尝试删除这样的群组:
using (var ctx = new ZoltarApp.Database.DatabaseContext())
{
ctx.Groups.Attach(group);
ctx.Groups.Remove(group);
}
我不想在删除群组时级联删除项目。
编辑:我仍然没有解决这个问题。有没有人知道答案?