Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use use Entity Framework to do a MERGE when I don't know if the record exists?

In this SO answer about Entity Framework and MERGE, the example for how to code it is this:

public void SaveOrUpdate(MyEntity entity) {   if (entity.Id == 0)   {     context.MyEntities.AddObject(entity);   }   else   {     context.MyEntities.Attach(entity);     context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);   } } 

This assumes that you already know if the entity that you want to upsert exists or not; in this case you check entity.Id. But what if you don't know if the item exists or not? For instance, in my case, I'm importing records from a vendor into my database, and a given record may or may not have already been imported. I want to update the record if it exists, otherwise add it. But the vendor's id is already set in both cases.

I can't see any way to do this unless I simply ask the database if the record is there already, which defeats the whole purpose of MERGE.

like image 895
Joshua Frank Avatar asked May 28 '14 15:05

Joshua Frank


People also ask

Why you should not use Entity Framework?

One of the biggest reasons not to use Entity Framework Core is that your application needs the fastest possible data access. Some applications do a lot of heavy data operations with very high-performance demands, but usually business applications don't have that high of a performance demand.

Can Entity Framework work without primary key?

Because Entity Framework is able to modify data in your database it needs a primary key to be defined in order for it to be able to uniquely identify rows.

Should I use Entity Framework or dapper?

Dapper is literally much faster than Entity Framework Core considering the fact that there are no bells and whistles in Dapper. It is a straight forward Micro ORM that has minimal features as well. It is always up to the developer to choose between these 2 Awesome Data Access Technologies.


1 Answers

I use AddOrUpdate in this situation. However, I believe it does query the database first in order to decide to issue an insert or update.

context.MyEntities.AddOrUpdate(e => e.Id, entity); 

Update:

I ran through my debug log files. First it runs:

SELECT TOP (2) ... WHERE 1 = [Extent1].[Id] 

Then it runs either:

INSERT [dbo].[TestTable](...) VALUES (...) SELECT [Id] FROM [dbo].[TestTable] WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity() 

OR:

UPDATE [dbo].[TestTable] SET ... WHERE ([Id] = @2) 

Update 2: Here's an interesting extension method the uses MERGE: https://gist.github.com/ondravondra/4001192

like image 88
Robert Graves Avatar answered Nov 04 '22 06:11

Robert Graves