entity-framework - 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
解决方案
您必须手动更新它,ef core 无法自动检测到更改。看到这个答案
推荐阅读
- java - StreamResource 有时在关闭对话框窗口中单击下载按钮时找不到资源
- javascript - 为什么在使用 for 循环添加事件侦听器时会出现 TypeError?
- javascript - 当我使用 for 或 while 循环时,我的应用程序崩溃了
- c++ - glGenVertexArrays 上的 OpenGL C++ glfw 3 glew 错误 1282
- javascript - 在 IE 8 中显示图像,image/abc.gif 和 image\abc.gif 都可以正常工作,但在 IE 11 中却不是。有人可以帮我解决这个问题吗
- r - 如何在没有任何其他依赖项(如 spark、python 等)的情况下将 parquet 文件读取为 R data.frame?
- vue.js - 动画菜单组件的问题
- amazon-web-services - 必须批量移动文件的 Minio/S3 场景
- webrtc - Google Chrome M74 对 WebRTC 的 mDNS 支持
- react-native - React-native build android fail dismatch react-native模块编译版本和运行时版本错误