Question

I am using Entity Framework and part of my code want to put say 100 entities to the database. Some of the entities that I am inserting have many to many relationship and I want to make sure that I am inserting only new items. It is easy to check the existing ones in the db but if I have already inserted it in my current session to persist the 100 items, I will get repeated items.

The thing is the primary key are just auto generated and the table uniqueness comes from a unique column which is not supported in EF. How do I check if I have not already inserted the item part of my session in EF 4.1? I saw the find method on the DbContext but that needs primay key which I can not use. Given that I use 4.1, I am stuck with DBContext too. HOw can I have a generic way to check this?

Was it helpful?

Solution

If you want to use EF you should stick with PK as unique identification of your entities. Otherwise your development experience will be pretty bad.

If you want to check if you already processed the same item in the current context use:

bool exists = context.YourDbSet.Local.Any(x => x.UniqueId == someId)

If you need to check the state of the entity use:

EntityState state = context.Entry(entity).State;

If you need to check if the entity exists in the database use:

YourEntity entity = context.YourDbSet.SingleOrDefault(x => x.UniqueId == someId);

The last statement is actually not a best way in concurrent system because when you call it the entity doesn't have to exist but once you call SaveChanges other process could already inserted the entity. There is no easy way to deal with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top