EntityFramework .net 4 Update entity with a simple method

前端 未结 1 763
谎友^
谎友^ 2021-01-03 09:05

I was looking at this SO question: ADO.net Entity Framework: Update only certian properties on a detached entity. This was a big help for me. I know now that I need to attac

相关标签:
1条回答
  • 2021-01-03 09:45

    Try something like this (pseudo code, I might have misremembered some method names):

    public void Update(Customer entity)
    {
    
       using (MyContext ctx = new MyContext())
       {
          // Create a stub entity and attach it
          Customer db = new Customer {ID = entity.ID};
          ctx.Customers.Attach(db); // ctx.AttachTo("Customers", db) in 3.5 sp1
    
          // ApplyPropertyChanges in 3.5 Sp1
          ctx.ApplyCurrentValues(entity); 
          ctx.SaveChanges();
       }
       ...
    }
    

    This code uses the Stub Entity trick. You may if you have relationships need to tell EF more about the original entity, check out the blog post above for more because you can do that using stubs too.

    Alternatively if you don't care at all about concurrency you could just do this:

    public void Update(Customer entity)
    {
       using (MyContext ctx = new MyContext())
       {
          // pull the entity from the database
          Customer db = ctx.Customers.First(c => c.ID == entity.ID);
    
          // ApplyPropertyChanges in 3.5 Sp1
          ctx.ApplyCurrentValues(entity); 
          ctx.SaveChanges();
       }
    }
    

    Hope this helps

    Alex James

    Entity Framework Tips

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