Does EF upsert have to be done manually?

public void InsertOrUpdate(DbContext context, UEntity entity)
{
    context.Entry(entity).State = entity.Id == 0 ?
                                   EntityState.Added :
                                   EntityState.Modified;
    context.SaveChanges();
}

http://forums.asp.net/t/1889944.aspx/1


To avoid the overhead of a query and then insert, or throwing exceptions, you can take advantage of the underlying database support for merges or upserts.

This nuget package does the job pretty well: https://www.nuget.org/packages/FlexLabs.EntityFrameworkCore.Upsert/

Github: https://github.com/artiomchi/FlexLabs.Upsert

Example:

DataContext.DailyVisits
    .Upsert(new DailyVisit
    {
        // new entity path
        UserID = userID,
        Date = DateTime.UtcNow.Date,
        Visits = 1,
    })
    // duplicate checking fields
    .On(v => new { v.UserID, v.Date })
    .WhenMatched((old, @new) => new DailyVisit
    {
        // merge / upsert path
        Visits = old.Visits + 1,
    })
    .RunAsync();

The underlying generated sql does a proper upsert. This command runs right away and does not use change tracking, so that is one limitation.


See 'AddOrUpdate' method of System.Data.Entity.Migrations.
http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.idbsetextensions.addorupdate%28v=vs.103%29.aspx

using System.Data.Entity.Migrations;

public void Save(Person person) {
    var db = new MyDbContext();
    db.People.AddOrUpdate(person);
    db.SaveChanges();
}