简体   繁体   English

在 Entity Framework 中修改同一个实体是否会同步将实体保存到数据库中? 抛出异常?

[英]Does modifying the same entity in Entity Framework will save the entity to the database synchronously? throw exception?

I'm investigating a bug in our systems and when reviewing the code I saw that the developer queried twice the same entity and saved it with different values.我正在调查我们系统中的一个错误,在查看代码时,我看到开发人员查询了两次相同的实体并使用不同的值保存它。

I simplified the case for example:我简化了案例,例如:

Person Data:
id  |   name    |   age |   HasLicence
1   |   david   |   27  |   true


using (DbContext dbContext = new DbContext())
{
    Person person1 = dbContext.Persons.FirstOrDefault(p=>p.age == 27);
    Person person2 = dbContext.Persons.FirstOrDefault(p=>p.name == "david");
    
    person1.HasLicence = false;
    person2.HasLicence = true;
    .
    .
    // more logic..
    .
    .
    dbContext.SaveChanges();
}

Does this will save the entity to the database synchronously?这是否会将实体同步保存到数据库中? throw exception?抛出异常?

Simple answer is both variables are referencing same object instance(proxy).简单的答案是两个变量都引用相同的 object 实例(代理)。

So when you update person1.HasLicence same value will be on person2.HasLicence.因此,当您更新 person1.HasLicence 时,person2.HasLicence 上会出现相同的值。

a.HasLicence = true;
Assert.AreEqual(a.HasLicence , b.HasLicence );

b.HasLicence = false;
Assert.AreEqual(a.HasLicence , b.HasLicence );

_dataContext.Save(); // updates only one entity

Behavior might be different if you have some changed settings for datacontext.如果您更改了数据上下文的设置,行为可能会有所不同。

IF you want to know more how entity frameworks works you can access it on github如果您想了解更多实体框架的工作原理,您可以在 github 上访问它

https://github.com/dotnet/ef6 https://github.com/dotnet/ef6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM