本文介绍了EF 4.1代码第一:类型中的每个属性名称必须是查找表关联时的唯一错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试创建我自己的EF模型,而且我发现自己试图使用Code First创建一个查找表关联,所以我可以访问:

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

我有设置模型和我明白正确的映射,但是继续获得
错误0019:类型中的每个属性名称必须是唯一的。属性名称CategoryID已被定义

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

我已经指定了与

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

我已经尝试了其他一些东西,包括添加[ForeignKey]注释,但是导致

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.

推荐答案

您正在寻找:

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

这篇关于EF 4.1代码第一:类型中的每个属性名称必须是查找表关联时的唯一错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 01:26