【问题标题】:EF Core Attach/Update Nested Object's Nested ObjectEF Core 附加/更新嵌套对象的嵌套对象
【发布时间】:2021-06-28 05:40:12
【问题描述】:

使用 .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-framework entity-framework-core


【解决方案1】:

您必须手动更新它,ef core 无法自动检测到更改。见this answer

【讨论】:

  • 这就是我害怕的。谢谢!
猜你喜欢
  • 2021-10-19
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 2021-12-15
  • 2015-06-25
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多