【发布时间】: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