Entity Framework Attach/Update confusion (EF Core)

拟墨画扇 提交于 2020-07-18 04:00:17

问题


As I understand, when "Update" is called, every property within a specific entity is modified.

The "Attach" method, on the other hand, starts the entity off in the "Unmodified" state. Then, when an operation takes place on a particular property, that specific property only is modified. So "Attach" is more useful for individual property changes, and "Update" is more useful when you want to update every property in the entity (I may be wrong in this understanding).

However, what I don't understand is what happens when neither of these two methods are called during a property change. For instance, consider an example with a table called "students":

student.City = "Calgary";
student.Name = "John Smith";
database.SaveChanges();

As we are not marking any property in the entity as modified, how will the generated query from the above code differ?


回答1:


Consider the following code:

students entity = new students() {
    Id = 1,
    City = "New York",
    Name = "Sam"
};
using(SomeContext ctx = new SomeContext())
{
    ctx.Entry(entity).State = EntityState.Modified;
    ctx.SaveChanges();
}

Assuming we have a record with id = 1 in the database, the above code will update that entity in the database.

Attach is used when you know that an entity already exists in the database but want to make some changes while change state to modified when you have already made the changes.



来源:https://stackoverflow.com/questions/50702865/entity-framework-attach-update-confusion-ef-core

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