sql - 使用 EntityFramework 6 更新具有相关对象的对象
问题描述
我正在尝试首先将 EF6 数据库集成到使用旧版 sql 的项目中。我对下表有疑问:
Product(ID, Name) -- this translates to a Product entity
User(ID, Name) -- this translates to a User entity
UserXProduct(UserID, ProductID) -- this translates into navigational properties
请注意,我无法通过实体框架访问 UserXProduct 表,因为它以某种方式没有生成新表,只是导航属性。我使用以下代码更新表:
var entity = ctx.User.SingleOrDefault(rec => rec.ID == updRec.ID);
if(entity != null){
entity.Product = ctx.Product.Where(rec => updRec.ProductIDs.Contains(rec.ID)).ToList();
ctx.SaveChanges();
}
它第一次工作,当用户记录没有任何与之关联的产品时,每当我将另一个产品添加到列表中时,它都会失败。
SQL Profiler 显示,Entity Framework 尝试将 UserID 和 ProductID 插入到 UserXProduct 表中,而不仅仅是新表,而是所有表。它应该要么删除以前的连接,要么只插入新的连接。我怎样才能实现这种行为?
解决方案
推荐阅读
- swift - 在转换对象 Swift 中设置值
- powershell - 使用 Visual Studio Code 查看我的函数的文档字符串
- plotly-dash - 向数据表添加行-加载依赖项时出错
- ios - 将视频资产保存到图库后检索
- python - 有没有办法更快地找到列表中的每个元素与该列表中的每个其他元素之间的差异?
- c++ - 重载函数的地址与所需类型不匹配
- html - 让 ap 元素动态填充(通过文本大小)父 div 的方法
- docker - Gitlab CI - 错误:作业失败:执行程序需要 OSType=linux,但 Docker 引擎仅支持 OSType=windows
- r - R:动态更新公式
- three.js - 如何将精灵定位在画布标注的特定点?