T
T
trauus2019-02-22 14:15:49
Entity Framework
trauus, 2019-02-22 14:15:49

How to implement association and cascading deletion in EntityFramework?

I am using EntityFramework 6.2 CodeFirst. Entities A and B contain collections of Record objects . In this case, Record can be contained in only one collection, and when A or B is deleted, all Record objects contained in their collections must also be deleted.
In the future, in addition to the entities A, B , others will be added, which will also contain collections of Record objects .
If you create a many-to-many relationship , then cascading deletion does not work. And .HasMany(a => a.Records).WithRequired() throws an exception.
How to properly implement the relationship so that cascading deletion works?

class Record
{
  public int Id {get; set;}
  public int Code {get; set;}
  public DateTime Date {get; set;}	
}

class A
{
  public int Id {get; set;}
  public ICollection<Record> Records {get; set;}
  public string Comment {get; set;}
}

class B
{
  public int Id {get; set;}
  public ICollection<Record> Records {get; set;}
  public DateTime CreationDate {get; set;}
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<A>()
    .HasMany(r => r.Records)
    .WithMany();

  modelBuilder.Entity<B>()
    .HasMany(i => i.Records)
    .WithMany();
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question