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

来源:互联网 发布:linux shell 小数运算 编辑:程序博客网 时间:2024/05/21 10:07

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

0 0
原创粉丝点击