KDr*_*ske 5 c# entity-relationship entity-framework entity-framework-4
这是我第一次尝试创建自己的EF模型,我发现自己试图使用Code First创建查找表关联,因此我可以访问:
myProduct.Category.AltCategoryID
Run Code Online (Sandbox Code Playgroud)
我已经设置模型和映射,因为我理解是正确的,但继续得到 错误0019:类型中的每个属性名称必须是唯一的.已定义属性名称"CategoryID"
以下模型在我的代码中表示:
[Table("Product", Schema="mySchema")]
public class Product {
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int ProductID { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
[Table("Category", Schema="mySchema")]
public class Category {
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string Name { get; set; }
public int AltCategoryID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我已经指定了以下关联:
modelBuilder.Entity<Product>()
.HasOptional(p => p.Category)
.WithRequired()
.Map(m => m.MapKey("CategoryID"));
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一些其他的东西,包括添加[ForeignKey]注释,但这会导致包含对ProductID字段的引用的错误.
您正在寻找:
modelBuilder.Entity<Product>()
// Product must have category (CategoryId is not nullable)
.HasRequired(p => p.Category)
// Category can have many products
.WithMany()
// Product exposes FK to category
.HasForeignKey(p => p.CategoryID);
Run Code Online (Sandbox Code Playgroud)