使用EntityFramework 6更新具有相关对象的对象

时间:2019-01-29 07:04:56

标签: sql .net entity-framework-6 foreign-keys entity

我正在尝试首先将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显示,实体框架尝试将UserID和ProductID插入到UserXProduct表中,不仅是新表,而且还包括所有表。它应该删除以前的连接或仅插入新的连接。我如何实现这种行为?

0 个答案:

没有答案
相关问题