实体框架更新操作 - 为什么儿童记录首先更新?

时间:2022-11-27 06:53:15

Background: i have a 1 to 0..1 relationship between User and UserSettings.

背景:我在User和UserSettings之间有1到0..1的关系。

The important part of the model is as follows:

该模型的重要部分如下:

public class User
{
   public int UserId { get; set; }
   public string Name { get; set; }
   public UserSettings Settings { get; set; }
}

public class UserSettings
{
   public int UserId { get; set; } // PK/FK
   public sting SpecialField { get; set; }
}

When i do an INSERT:

当我做INSERT时:

var user = new User { Settings = new UserSettings { SpecialField = "Foo" }};
ctx.Users.Add(user);
ctx.SaveChanges();

Everything is cool, when i check the trace, User is added first, then the UserSettings - as you would expect, since UserSettings needs the IDENTITY from User.

一切都很酷,当我检查跟踪时,首先添加用户,然后添加UserSettings - 正如您所期望的那样,因为UserSettings需要来自User的IDENTITY。

But when i UPDATE that "SpecialField":

但是当我更新“SpecialField”时:

var user = ctx.Users.Include("Settings").Single();
user.Name = "Joe";
user.Settings.SpecialField = "Bar";
ctx.SaveChanges();

I see that the trace shows EF updating the UserSettings first, then the User.

我看到跟踪显示EF首先更新UserSettings,然后是User。

Why?

This is important for me, because i have trigger logic that needs to execute only when SpecialField is changed, and it needs to reference data on User.

这对我很重要,因为我有触发逻辑,只有在更改了SpecialField时才需要执行,并且需要在User上引用数据。

Can anyone explain this behaviour? Is there a workaround (other than a hack - which would involve me manually "touching" special field again, which is really bad).

谁能解释这种行为?是否有一个解决方法(除了黑客 - 这将涉及我手动“再次触摸”特殊领域,这是非常糟糕的)。

2 个解决方案

#1


1  

Sorry, But I have tried your model in my PC. And All happened very well. User update first (Parent), then UserSetting (Child).

对不起,我已经在我的电脑上试过你的模型了。一切都很顺利。首先是用户更新(Parent),然后是UserSetting(Child)。

I think, It might be something wrong with your model setting or database setting, but I don't know what.

我想,你的模型设置或数据库设置可能有问题,但我不知道是什么。

#2


0  

Ended up "touching" the field again as a workaround.

结束了“触摸”该领域作为一种解决方法。

Damn you EF.

该死的EF。

#1


1  

Sorry, But I have tried your model in my PC. And All happened very well. User update first (Parent), then UserSetting (Child).

对不起,我已经在我的电脑上试过你的模型了。一切都很顺利。首先是用户更新(Parent),然后是UserSetting(Child)。

I think, It might be something wrong with your model setting or database setting, but I don't know what.

我想,你的模型设置或数据库设置可能有问题,但我不知道是什么。

#2


0  

Ended up "touching" the field again as a workaround.

结束了“触摸”该领域作为一种解决方法。

Damn you EF.

该死的EF。