Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MERGE in Entity Framework

Is there a way to call T-Sql's MERGE command from .NET Entity framework 4?

like image 603
alerya Avatar asked Apr 30 '11 13:04

alerya


People also ask

What is bulk merge?

The EF Bulk Merge feature lets you update thousands of entities in your database efficiently. This feature is provided by the library EF Extensions (Included with EF Classic). EF Extensions is used by over 2000 customers all over the world and supports all Entity Framework versions (EF4, EF5, EF6, EF Core, EF Classic).

Why does Entity Framework use Sp_executesql?

The use of sp_executesql is actually the only way to execute a parameterized dynamic SQL statement in SQL Server. There are two primary “execute” primitives in TDS, “batch” and “RPC”. A batch request just contains a T-SQL string, and can be used whenever there is no need for parameters.

Can I use Entity Framework and dapper together?

Important Aspect to Handle – Transactions Now, according to our requirement, we need both Entity Framework Core and Dapper to work alongside each other. This is quite easy to achieve actually.

Are Entity Framework extensions free?

Those features are free (even for commercial use) and will always be: Batch Delete. Batch Update. Batch Insert.


1 Answers

No there no such built-in functionality - you must build your own. Very common is for example approach like:

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

    // You can call SaveChanges here or you can call it separately after multiple changes
}

This is example for working with detached entity which have Id auto generated in the database (IDENTITY). Default Id for new entity is always 0 because the real value will be assigned during saving changes.

like image 192
Ladislav Mrnka Avatar answered Sep 22 '22 03:09

Ladislav Mrnka