实体框架附加/更新混淆 (EF Core) [英] Entity Framework Attach/Update confusion (EF Core)

查看:19
本文介绍了实体框架附加/更新混淆 (EF Core)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当调用更新"时,特定实体中的每个属性都会被修改.

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).

但是,我不明白的是,在属性更改期间这两种方法都没有被调用时会发生什么.例如,考虑一个名为students"的表的示例:

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?

推荐答案

考虑以下代码:

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

假设我们在数据库中有一条 id = 1 的记录,上面的代码将更新数据库中的那个实体.

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

Attach 用于当您知道一个实体已经存在于数据库中,但想要进行一些更改,同时在您已经进行更改时将状态更改为已修改.

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.

这篇关于实体框架附加/更新混淆 (EF Core)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆