我有一些POCO课程如下:
public class Inquiry
{
public Guid InquiryID { get; set; }
public Guid OwnerID { get; set; }
public User Owner { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime ModificationDate { get; set; }
public DateTime ExpirationDate { get; set; }
public decimal MaxPrice { get; set; }
public List<Region> Regions { get; set; }
}
public class Region
{
public Guid RegionID { get; set; }
public string Name { get; set; }
}
可以看出,查询与地区之间存在关联 - &gt;查询可能有很多地区。
概念模型如下:
区域通常是从数据库获取的预定义值 - 有16个区域。但是,查询可能有1个或更多区域。 当我尝试创建新查询(包含1个或更多区域)时,我得到以下异常:
违反PRIMARY KEY约束'PK_Region'。无法插入 对象'dbo.Regions
中的重复键
关于数据库:为了表示我在查询和区域之间的关联,我有一个名为InquiryRegions的表,其中包含以下列:
我想做什么: 当新查询添加到数据库时,不是将区域添加到表区域,而是通过向InquiryRegions表添加适当的行来分配具有查询的区域。
如何告诉EF不要将区域添加到表区域?
答案 0 :(得分:0)
我解决了我的问题,也许以下解决方案可以帮助别人。 首先,我必须将InquiryRegions数据库表和主键更改为列:
InquiryID (PK, FK, uniqueidentitier, not null) (reference to Inquiry table)
RegionID (PK, FK, uniqueidentifier, not null) (reference to Region table)
然后我必须明确地告诉EF这些区域已经存在并且不需要添加它们:
using(ApplicationEntities context = new ApplicationEntities)
{
foreach(var region in inquiry.Regions)
{
context.Regions.Attach(region);
}
}