Does EF upsert have to be done manually?

前端 未结 4 661
忘了有多久
忘了有多久 2021-02-01 04:39

I want to upsert reference members of an existing entity.

Do I have to write specific code for the upsert?

meaning: I have to check if I\'m handling an existing

相关标签:
4条回答
  • 2021-02-01 04:45

    "optimistic" approach for simple scenarios (demos)... dbContext.Find()'s intellisense help tells us that it either retrieves entity by key if already present in current context, or queries the database to get it... then we know if it exists to either add or update. i'm using EFCore v2.2.0.

      var existing = _context.Find<InventoryItem>(new object[] {item.ProductId});
      if (existing == null) _context.Add(item);
      else existing.Quantity = item.Quantity;
      _context.SaveChanges();
    
    0 讨论(0)
  • 2021-02-01 04:54

    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.

    0 讨论(0)
  • 2021-02-01 05:01

    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();
    }
    
    0 讨论(0)
  • 2021-02-01 05:03
    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

    0 讨论(0)
提交回复
热议问题