EF 4.1 Code First: Each property name in a type mu

2020-07-14 09:23发布

问题:

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