在ef中,CUD都使用Datacontext.SaveChange()进行保存.
SavaChange方法在保存之前会自动调用DetectChanges方法检查DataContext中做了什么更改,以作出对应的数据库操作.
create 增
dbcontext.dbset.add(model),然后再调用datacontext.savechanged();
using (var context = new BookStore()) { Author author = new Author() { FirstName = "Mark", LastName = "Johny", }; context.Authors.Add(author); context.SaveChanges(); }
update 改
using (var context = new BookStore()) { var author = context.Authors .FirstOrDefault(); author.LastName = "Cuban"; context.SaveChanges(); }
delete 删
datacontext.dbset.remove(model); 再datacontext.savechangs();
如果model不在数据库中则从datacontext中删除,否则数据库和datacontext都会删除.
using (var context = new BookStore()) { var author = context.Authors .Where(a => a.AuthorId == 2) .FirstOrDefault(); context.Authors.Remove(author); context.SaveChanges(); }