asp.net mvc - Entity framework inserts new record to navigation table inappropriately -
i'm facing issue when inserting records many many navigation property,
i have these models
//modelbase public class modelbase { [key] public long id { get; set; } } //book public class book : modelbase { public string title { get; set; } public virtual icollection<author> authors { get; set; } public virtual icollection<publishedbook> publishedbooks { get; set; } } //author public class author : modelbase { public string name { get; set; } public virtual icollection<book> books { get; set; } }
and dtos called bookdto
, authordto
transfer data between layers
from controller fill data dtos , call create
method (which in separate layer) save data database,
bookdto bookdto = new bookdto() { id = model.id, title = model.title, authors = model.authorids.select(c => new authordto { id = c }).tolist() } using (servicefactory facory = new servicefactory()) { factory.book.create(bookdto); }
in create
method map dtos pocos using valueinjector
public void create(bookdto bookdto) { book book = new book(); book.injectfrom<deepcloneinjection>(bookdto); bookrepository.add(book); unitofwork.commit(); }
and calls add
method in genaric repository base
public virtual void add(t entity) { dbset.add(entity); }
this inserts data books
table , bookauthors
tables appropriately inserts new record authors
table if pass authors
has existing authorids
book.authors
controller.
any idea how fix this?
you missing attach existing authors context. so:
public void create(bookdto bookdto) { book book = new book(); book.injectfrom<deepcloneinjection>(bookdto); foreach (var author in book.authors) authorrepository.attach(author); bookrepository.add(book); unitofwork.commit(); }
where generic attach
methods implemented calling dbset.attach(entity);
. assuming repositories (authorrepository
, bookrepository
) share same context instance. otherwise above won't work.
the fact authorid
exists in database doesn't matter. ef doesn't check if id exists query first. if call add
on object graph of detached entities tries insert whole graph generating insert statements parent , children. attaching children turn off insert statements those.
Comments
Post a Comment