entity framework 5, delete one to many relationship? -


the relationship of entity a,b one-to-many, (a has many bs, b must belong a).

i disabled lazy loading , load a, b this:

dbcontext.as.load(); //**particaly load b**  dbcontext.bs.where(predicatex).load(); 

when use

dbcontext.as.remove(somea) 

to delete a, encounter following error message

the relationship not changed because 1 or more of foreign-key properties non-nullable

instead, if use:

//remove b in somea foreach(b b in somea.bs.tolist()) {    dbcontext.bs.remove(b); } dbcontext.as.remove(somea) 

everything ok.

is there better way this?

edit


i using database first , add foreign key constraint of b (on delete cascade) @ database side.

i think "the foreign key constraint" equal code "onmodelcreating". code "dbcontext.as.remove(somea)" doesn't work expected.

things worse when there a-b-c cascade 1 many relation.in order delete somea,you need 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); 

solved:


i use database first(sqlite) , add foreign key constraint @ database side.

use vs2012 create edmx sqlite database file,

vs2012 failed set "on delete cascade" property of relationship.

after manual set property,single call "dbcontext.as.remove(somea)" work expected!

sadly, there (currently) no batch support in entity framework, you're stuck foreach-ing through multiple properties. might want @ entityframework.extended project, adds various batch operations tidy code (as improving performance).

if you're sure you'll want delete related b's when deleted, configure relationship use "on delete cascade" behaviour. means when parent deleted, of child b's automatically deleted well. how depends on how you've created database. if you're using code first, it'll this:

public class mycontext : dbcontext {     public dbset<a> { get; set; }     public dbset<b> bs { get; set; }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {         modelbuilder.entity<a>()                     .hasmany(a => a.bs)                     .withrequired(b => b.a)                     .willcascadeondelete();     } } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -