Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework UPDATE Operation - Why is child record updated first?

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

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:

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.

But when i UPDATE that "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.

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.

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

like image 692
RPM1984 Avatar asked Nov 13 '22 21:11

RPM1984


1 Answers

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

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

like image 54
Agus Syahputra Avatar answered Dec 11 '22 10:12

Agus Syahputra