EF 4.1 Code First: Each property name in a type must be unique error on Lookup Table association

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

This is my first attempting at creating my own EF model, and I'm finding myself stuck attempting to create a lookup table association using Code First so I can access:

myProduct.Category.AltCategoryID 

I have setup models and mappings as I understand to be correct, but continue to get error 0019: Each property name in a type must be unique. Property name 'CategoryID' was already defined

The following models are represented in my code:

[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; } } 

I have specified the associations with:

modelBuilder.Entity<Product>()                     .HasOptional(p => p.Category)                     .WithRequired()                     .Map(m => m.MapKey("CategoryID")); 

I've tried a few other things, including adding the [ForeignKey] annotation, but that results in an error containing a reference to the ProductID field.

回答1:

You are looking for:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!