问题
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