开发者

Check items are not inserted in Entity Framework 4.1

开发者 https://www.devze.com 2023-03-12 01:24 出处:网络
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

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 tabl开发者_JAVA百科e 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消