Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 215
KDrewiske Avatar asked Jun 29 '11 19:06

KDrewiske


1 Answers

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);
like image 197
Ladislav Mrnka Avatar answered Nov 09 '22 07:11

Ladislav Mrnka