首页 > 解决方案 > EF Core 附加/更新嵌套对象的嵌套对象

问题描述

使用 .Includes 和 .ThenIncludes 检索数据非常有意义且有效,太棒了!然后我的问题是更新第三级。这是在断开连接的情况下发生的,下面的代码已针对示例进行了简化。如果您可以检索 n 级深的数据,那么您肯定可以更新 n 级深的数据,对吧?

public class Person
{
public int id { get; set; }
    public int? Address { get; set; }

    public virtual Address AddressNavigation { get; set; }
}

public class Address
{
    public int id { get; set; }
    public string Street { get; set; }
    public string Street2 { get; set; }
    public int? City { get; set; }
    public int? State { get; set; }
    public string Zip { get; set; }

    public virtual City CityNavigation { get; set; }
    public virtual State StateNavigation { get; set; }
}

public class City
{
    public int id { get; set; }
    public string Name { get; set; }
}

public class State
{
    public int id { get; set; }
    public string Name { get; set; }
}

现在,如果我想更新城市或州,我似乎可以执行以下操作:

person.AddressNavigation.CityNavigation.id = 2;

context.Attach(person);
context.Entry(person).State = EntityState.Modified;
context.SaveChanges();

但是,发生的情况是,一旦调用了 .Attach,person.AddressNavigation.CityNavigation.id 的先前值就会更改回原始值,从而不会将更改保存到数据库中。为什么会这样?我目前正在使用 EF Core 5.0.5

标签: entity-frameworkentity-framework-core

解决方案


您必须手动更新它,ef core 无法自动检测到更改。看到这个答案


推荐阅读