Entity structure 5, delete one for many relationships?

The relation of entity A, B is one to many (A has many Bs, B must belong to A).

I disabled lazy loading and downloaded A, B as follows:

 dbContext.As.Load(); //**particaly load B** dbContext.Bs.Where(predicateX).Load(); 

When i use

 dbContext.As.Remove(someA) 

To remove A, I encounter the following error message

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Instead, if I use:

 //remove all B in someA foreach(B b in someA.Bs.ToList()) { dbContext.Bs.Remove(b); } dbContext.As.Remove(someA) 

everything is good.

Is there a better way to do this?

Edit


I use Database First and add the foreign key constraint B (when deleting the cascade) from the database side.

I think the "foreign key constraint" just matches the code for "OnModelCreating". but the code "dbContext.As.Remove (someA)" does not work properly.

the situation gets worse when there is an ABC cascade from one to a large ratio. To remove someA, you need to do this:

 foreach(B b in someA.Bs.ToList()) { foreach(C c in b.Cs.ToList()) { dbContext.Cs.Remove(c); } dbContext.Bs.Remove(b); } dbContext.As.Remove(someA); 

It is decided:


i first use the database (sqlite) and add a foreign key constraint on the database side.

use vs2012 to create edmx from sqlite database file,

vs2012 could not set the property "on delete cascade" of the relationship.

after manually setting the property, one call to "dbContext.As.Remove (someA)" works properly!

+6
source share
1 answer

Unfortunately, there is no (currently) batch support in the Entity Framework, so you stuck foreach through several properties. You might want to look at the EntityFramework.Extended project, which adds various batch operations to remove such code (as well as improve performance).

If you are sure you always want to delete the associated B when you delete A, adjust this relation to use the "on delete cascade" behavior. This means that when parent A is deleted, all of its children B are also automatically deleted. How to do this depends on how you created the database. If you use Code First, it will be something like this:

 public class MyContext : DbContext { public DbSet<A> As { get; set; } public DbSet<B> Bs { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<A>() .HasMany(a => a.Bs) .WithRequired(b => bA) .WillCascadeOnDelete(); } } 
+7
source

Source: https://habr.com/ru/post/951293/


All Articles