When to call SaveChanges

馋奶兔 提交于 2019-12-09 17:56:10

问题


Say I have something like this that is called in Controller:

using (var context = new SqlContext())
{
    context.Items.Add(new Item("item1"));
}

Should I be calling context.SaveChanges();?


回答1:


entity framework implements a unit of work pattern with DbContext this means that you define a package of things you want to do to your database and then call save changes to propogate them all to the database at once. All operations will be executed within a single transaction (for a single saveChanges call) which means that either all or none will be propogated to the database at once.

Before calling save changes, the changes are applied to your local tracking graph but not to the database itself until savechanges is called.




回答2:


yes.

every change you make won't be saved until context.SaveChanges(); is called.

Note that if you will have an object from other DbContext (which is absolutly not the situation you gave) you should need to change the entity state explicitly by using these lines of code instead:

Item item = new Item("item1")
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();


来源:https://stackoverflow.com/questions/14269765/when-to-call-savechanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!