How do I upsert a record in ADO.NET EF 4.1?

后端 未结 5 1980
走了就别回头了
走了就别回头了 2021-01-01 23:22

I\'m trying to accomplish something really simple and I can\'t find how to do it using Entity Framework 4.1.

I want a controller method that accepts an object and

5条回答
  •  醉酒成梦
    2021-01-01 23:52

    Unfortunately there is no way to do this without querying database or using stored procedure. The minimalistic code should be:

    public void AddOrModify(T entity, string key) where T : class, IEntity // Implements MyKey 
    {
         using (var context = new MyContainer())
         {
             if (context.Set().Any(e => e.MyKey == key))
             {
                  context.Entry(entity).State = EntityState.Modified;
             } 
             else
             {
                  context.Entry(entity).State = EntityState.Added;
             }
    
             context.SaveChanges();
         }
    }
    

提交回复
热议问题