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

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

问题描述

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

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?

推荐答案

请考虑以下代码:

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 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核心)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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