entity framework - ef code first many to many saving just relationship for existing items -
i'm using ef 6 code first manage db. have task class such
public class task{ public guid id { get; set; } public icollection<timeframe> timeframes { get; set; } }
and timeframe class looks like
public class timeframe{ public guid id { get; set; } public icollection<task> tasks { get; set; } }
this created right many many table structure. application workflow such task , timeframe both going exist before task/timeframe relationship saved. i'm having problem getting relationships persist 1 time created. understand relationships not taken business relationship when set entity entitystate.modified
, have modify collection in order relationship persist. i'm using next code update task.timeframes collection attached timeframes thought work
public void savetask(task task) { entities.tasks.attach(task); var timeframes = new list<timeframe>(); foreach (var tf in task.timeframes) { entities.timeframes.attach(tf); timeframes.add(tf); } entities.entry(task).state = entitystate.modified; task.timeframes.clear(); timeframes.foreach(t => { task.timeframes.add(t); }); entities.changetracker.detectchanges(); entities.savechanges(); }
but relationship still not beingness persisted. looked relationshipmanager manually set relationship added, can't figure out how if exists in ef6. doing wrong keeping relationships persisting?
with farther research , this answer, able add together using system.data.entity.infrastructure;
, alter persistence code to
public void savetask(task task) { entities.tasks.attach(task); var objectcontext = ((iobjectcontextadapter)entities).objectcontext; foreach (var tf in task.timeframes) { entities.timeframes.attach(tf); objectcontext.objectstatemanager.changerelationshipstate(task, tf, t => t.timeframes, entitystate.added); } }
and relationships persisted. didn't expect have managed quite manually, help else in same situation.
entity-framework ef-code-first
No comments:
Post a Comment