【发布时间】:2014-06-15 23:16:40
【问题描述】:
我在这个问题上玩了几天,找不到任何解决方案。
我使用的是代码优先策略,.NET MVC 4.5 和 EF 6
我有两个带有复合键的模型:
public class Category : DbContext
{
[Key, Column(Order = 0),DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; set; }
[Key, Column(Order = 1)]
public int ShopId { get; set; }
public string Name { get; set; }
}
public class Product : DbContext
{
[Key, Column(Order = 0),DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductId { get; set; }
[Key, Column(Order = 1)]
public int ShopId { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId, ShopId")]
public virtual Category Category { get; set; }
}
当我要运行 add-migration 命令时,我会在迁移文件夹中获得以下代码:
CreateTable(
"dbo.Categories",
c => new
{
CategoryId = c.Int(nullable: false, identity: true),
ShopId = c.Int(nullable: false),
Name = c.String(nullable: false, maxLength: 5)
})
.PrimaryKey(t => new { t.CategoryId, t.ShopId });
CreateTable(
"dbo.Products",
c => new
{
ProductId = c.Int(nullable: false, identity: true),
ShopId = c.Int(nullable: false),
CategoryId = c.Int(nullable: false)
})
PrimaryKey(t => new { t.ProductId, t.ShopId })
.ForeignKey("dbo.Categories", t => new { t.CategoryId, t.ShopId }, cascadeDelete: true)
.Index(t => new { t.ShopId, t.CategoryId });
然后,当我运行 update-database 命令时,一切正常,直到第一次通过 EF 访问数据库。我会收到这个错误:
表 Product (ShopId, CategoryId) 转表 Category(CategoryId, ShopId):: 不足 映射:外键必须映射到某个 AssociationSet 或 参与外键关联的实体集 概念方面。
现在的我:
如果我从 Model 类中删除外键,EF 仍会为迁移代码生成外键。问题仍然存在。
如果我从生成的迁移代码中删除外键。问题仍然存在。 (即使在 DB 中表之间没有任何外键)
如果我将 Product 类属性 CategoryId 从 int 更改为 string,EF 将为表 Product_CategoryId 和 Product_ShopId 生成新的两列,并将外键放在这些列上。问题解决了……
真的不明白哪里出了问题。当然我不想在表格中有这两列。我想从 CategoryId 和 ShopId 列中获得直接外键。
真的很感谢。任何建议。
【问题讨论】:
标签: c# database entity-framework foreign-keys