ASP.NET EF4: adding duplicate referenced entities
I have a newly entity framework 4 entity that references another entity, a simple user record. In my input data, I may have multiple instances of user records that are the same person. That person may not exist in the database; if not, I need to add them by creating a new user entity and adding them.
So when I create the main entity that references the user, I do a quick lookup for that user in the database. If that person exists, great, I got the reference to set. If not, I create a new user record and set the reference in the main entity to the newly created user entity. As I process more records, the same user may pop up, so when I do the query in the "create new user" function, I was assuming that if a newly created but not yet saved entity existed, the query would find that record, but apparently not (ok maybe dumb assumption)... so end result is that a duplicate record is created for that user, linked up to the new main entity, and when it is all saved, I get a "SQL Error 2601: Cannot insert duplicate key row in object 'dbo.user_table' with unique index 'IX_user_table'." error.
So I'm a bit baffled how to resolve this situation. The problem is that I can't call SaveChanges() on the context right after adding a new user entity because that causes the entire entity graph to be saved, and the main entity that is referencing the user records is not yet complete, it is not ready to save, so I can't save the whole mess every time开发者_开发技巧 I add a new user. I need to construct all the entities then save it all in one shot.
Do I need to do two queries every time I look up a user, one on the database and one something like:
var unsavedVisitors = from c in
dataContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added)
where c.Entity is my_table
select c.Entity;
I really haven't fiddled with the internals of the entity state manager so I'm not sure what to do here - how can I do a query to find an existing yet unsaved user entity that I could then just link up to the new main entities I'm creating as I loop through my input data? It looks like I can just cast c.Entity above to my_table type and wala, I've got my reference. I wish there was just some kind of "include unsaved entities in my query" trick or something, to avoid walking all the unsaved entities with so many queries - is there?
No, there is no "include unsaved entities in my query" trick. It's the right way to check for entries in the ObjectStateManager
. Alternatively you could manage the new added users in some custom dictionary but that's basically the same like leveraging the ObjectStateManager. Last option would be to clean up somehow your collection of users from duplicate objects in the first place.
精彩评论