简体   繁体   中英

Entity Framework creates duplicates if assign object

Hello I've created a small WPF application using PRISM and Unity, Entity Framework.

I have a sharedInfo class for accessing the currently logged in user which I populate in my bootstapper if database contains a user matching the details entered by user.

My users can create notes on certain entities and I want to know who created the note so my note class has a navigation property of SystemUser. If I create a new note and set the property like so:

note.SytemUser = _unityContainer.Resolve<ISharedInfo>("AppSharedInfo").LoggedInUser;

then when I save the details I get a new systemUser created. This does not happen if I simply set the Id property like so:

note.SystemuserId =_unityContainer.Resolve<ISharedInfo>("AppSharedInfo").LoggedInUser.SystemUserId;

This seems wrong to me, can you tell me where I am going wrong here and what is causing the duplication of my user details if I set the notes' SystemUser property?

Most likely you add the note to your context somewhere like so:

context.Notes.Add(note);

This line does not put only the note itself into Added state but also all related objects of note that are not yet known to the context instance, that is related objects that are in state Detached . In order to avoid that related entities are added as well you must tell EF explicitly that you know that the related entity already exists by attaching it to the context (in state Unchanged ) before you call Add for the note :

context.SystemUsers.Attach(note.SystemUser);
context.Notes.Add(note);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM