Can EF automatically delete data that is orphaned, where the parent is not deleted?

前端 未结 5 1944
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 21:24

For an application using Code First EF 5 beta I have:

public class ParentObject
{
    public int Id {get; set;}
    public virtual List Ch         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 21:51

    It is actually supported but only when you use Identifying relation. It works with code first as well. You just need to define complex key for your ChildObject containing both Id and ParentObjectId:

    modelBuilder.Entity()
                .HasKey(c => new {c.Id, c.ParentObjectId});
    

    Because defining such key will remove default convention for auto incremented Id you must redefine it manually:

    modelBuilder.Entity()
                .Property(c => c.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    

    Now calling to parentObject.ChildObjects.Clear() deletes dependent objects.

    Btw. your relation mapping should use WithRequired to follow your real classes because if FK is not nullable, it is not optional:

    modelBuilder.Entity().HasMany(p => p.ChildObjects)
                .WithRequired()
                .HasForeignKey(c => c.ParentObjectId)
                .WillCascadeOnDelete();
    

提交回复
热议问题