Using the model above, I am trying to save a new PamNewsMessage
and add Tags to it then save it to the DB. However, after trying many different combinations of adding objects and saving, I still have the same problem with duplicate entries (not duplicate key开发者_如何学Cs).
Currently, this is what I am using to make the changes, and it works for the PamNewsMessage
, however if a Tag already exists, it makes a duplicates.
_theService = new WCFPamUpdateServiceEntities3();
_theService.PamNewsMessages.AddObject(pnm);
_theService.SaveChanges();
I am not sure what else I need to do here, it should be pretty straight forward. I have read a lot of people having similar problems with no clear fix that I have found. Can anybody help me out here I have messed around with this for many hours now reading and trying different combinations of ways to save things, changing states, and what not.
Thanks,
Richard
Sorry about not being able to post pictures, long time reader first time poster :-)
Here is little bit theory when I met the problem first time. Here is some description related to EF.
Short answer is: EF will not do this for you.
You worked with detached objects and now you must explicitly tell EF what changes you did = it generally means playing with state of every entity in the graph and every independent association in the graph (many-to-many is always independent association). If you call AddObject
you are telling EF to add whole object graph not only the single entity.
If you just know that you are adding NewsMessage and this message will have only existing Tags you can do something like:
_theService = new WCFPamUpdateServiceEntities3();
_theService.PamNewsMessages.AddObject(pnm);
foreach (var tag in pnm.Tags)
{
_theService.ObjectStateManager.ChangeObjectState(tag, EntityState.Unchanged);
}
_theService.SaveChanges();
Obviously once you go to more complicated scenarios where you can also add new tags or remove connections to existing tags this simple solution will not work.
精彩评论