Reputation: 15069
I have a group of entities that I don't know if they already exists in the Database. If they exists - I need to update them, if they does not exists - I need to add them (for each entity it might be one or the other, and there are 10000 of them...)
(scenario - I'm importing data from a file, if I import the same file - nothing should happen, if the file is changed - I need to update).
Can I achieve it with Entity Framework without having to search for each entity before I add it ?
(if I want to add - I need to use AddObject, if I want to modify - I need to use attach and ChangeObjectState).
is there a way to avoid the search - than do one of the 2 options ?
(looking for "Add or Update" way....)
Thanks.
Upvotes: 0
Views: 2515
Reputation: 6050
If you can use the DbContext API (EF 4.3 and EF 5), you can use the AddOrUpdate method. You get sample code showing usage of this method when you enable Migrations, or you can see an example in this older blog post from the EF team:
Upvotes: 1
Reputation: 364279
No. In EF you must know if you want to insert or update the entity => if you don't know it you must first search the database. You can reduce the complexity by not using EF and use SQL directly but you will still have to search for the entity before you decide to insert or update. In case of direct SQL this whole can be done in the single database roundtrip (SQL Server 2008 offers special command MERGE
this) whereas EF needs separate roundtrip for search and separate roundtrip for update or insert.
Edit: Another solution with better performance would be to fetch all data to database by some quick way - for example temporary table filled by stored procedure with table valued parameter or with bulk insert. Once you have all records in some processing table you can use SQL to update all records existing in real table and insert all not existing records.
Upvotes: 2