EF 4 insert entity in relationship with existing entity
using (EntitiesContainer开发者_开发知识库 db = new EntitiesContainer())
{
Language language = db.Languages.SingleOrDefault(x => x.Culture == _session.Language);
Language language2 = new Language { Id = action.Language.Id };
Operation operation = new Operation { Id = action.Operation.Id };
//Operation operation = db.Operations.SingleOrDefault(x => x.Id == action.Operation.Id);
if (!language.Id.Equals(language2.Id))
{
db.Languages.Attach(language2);
action.Language = language2;
}
else
{
action.Language = language;
}
db.Operations.Attach(operation);
//db.ObjectStateManager.ChangeObjectState(operation, System.Data.EntityState.Unchanged);
action.Operation = operation;
//operation.Internals.Add(action);
action.CurrentDetail.Language = language;
action.CurrentDetail.Id = Guid.NewGuid();
action.Id = Guid.NewGuid();
db.SaveChanges();
}
Hello I Try all this scenario in commentary, for link my existing operation to the internal action that inherited from action .. but in any of this scenario, he throw me an error like he want to insert a new operation in the DB (dbo.Operations can accept "Action" NULL value) but the Entity already exist.. Can someone please, give me the golden rule .. to insert entity with relation .. existing or not in EF. It's driving me crazy!
Cordialy, Julien.
If i understand you correctly (your trying to update a relationship), you can use the stub technique:
Language lang = new Language { Id = action.language_id }; // create stub with ID
db.Languages.Attach(lang); // attach stub to graph
action.language = lang; // update relationship
db.SaveChanges();
精彩评论