首页 > 解决方案 > 使用 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 表中,而不仅仅是新表,而是所有表。它应该要么删除以前的连接,要么只插入新的连接。我怎样才能实现这种行为?

标签: sql.netentity-framework-6foreign-keysentity

解决方案


推荐阅读