LINK - EF6 Update/Insert/Delete model object from outside of DbContext

Update or Insert:

public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        context.Entry(blog).State = blog.BlogId == 0 ? 
                                   EntityState.Added : 
                                   EntityState.Modified; 
 
        context.SaveChanges(); 
    } 
}

reference - https://msdn.microsoft.com/en-us/data/jj592676.aspx


Delete by PK:

Customer customer = new Customer () { Id = id };
context.Customers.Attach(customer);
context.Customers.Remove(customer);
context.SaveChanges();

reference - http://stackoverflow.com/a/28050510


Partial Update:

public void ChangePassword(int userId, string password)
{
  var user = new User() { Id = userId, Password = password };
  using (var db = new MyEfContextName())
  {
    db.Users.Attach(user);
    db.Entry(user).Property(x => x.Password).IsModified = true;
    db.SaveChanges();
  }
}

reference - http://stackoverflow.com/a/5567616

你可能感兴趣的:(LINK - EF6 Update/Insert/Delete model object from outside of DbContext)