我具有通过对数据库表进行反向工程创建的以下实体:
public partial class Item
{
public int ItemId{ get; set; }
public int ItemTypeId{ get; set; }
public int ItemCategoryId{ get; set; }
public ItemType ItemType{ get; set; }
public ItemCategory ItemCategory { get; set; }
}
public partial class ItemCategoryType
{
public ItemCategoryType()
{
Items = new HashSet<Item>();
}
public int ItemCategoryTypeId { get; set; }
public string ItemCategoryTypeName { get; set; }
public ICollection<Item> Items { get; set; }
}
public partial class ItemType
{
public ItemType()
{
Items = new HashSet<Item>();
}
public int ItemTypeId { get; set; }
public string ItemTypeName { get; set; }
public ICollection<Item> Items { get; set; }
}
然后我将我的Items模型搭建支架以创建粗略设置。
我的问题是,当我尝试创建商品时,出现以下错误:
SqlException:INSERT语句与FOREIGN冲突 密钥约束“ FK_Items_ItemCategoryTypes”。冲突 发生在数据库“ xxx”,表“ xxx.ItemCategoryTypes”中, 列“ ItemCategoryTypeId”。
为什么会这样?另一个奇怪的是,在我的脚手架页面中,ItemTypes准确地映射到了ItemTypeName列表。但是,项目类别使用ItemCategoryTypeId而不是ItemCategoryTypeName绑定到列表。
考虑到模型的设置相同且除了字段名称之外,其他模型彼此相似,因此实体框架如何知道要绑定到哪个字段。
这种不一致可能是导致错误的原因,因为当我创建新商品时,实体框架正尝试插入商品类别记录。相反,它应该只是将所选的ItemCategoryId分配给创建的新项目记录。