实体框架中的外键4.1

Dot*_*row 23 .net data-annotations ef-code-first entity-framework-4.1

我正在使用Entity Framework 4.1并使用外键的数据注释.我想知道如何定义产品和类别之间的一对多关系.我想要分类.categoryId with product.cid

public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CId { get; set; }

    public virtual Category Category { get; set; }
} 
Run Code Online (Sandbox Code Playgroud)

请建议

Lad*_*nka 24

这两种方法都应该有效:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    [ForeignKey("Category")]
    public string CId { get; set; }

    public virtual Category Category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

要么:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CId { get; set; }

    [ForeignKey("CId")]
    public virtual Category Category { get; set; }
} 
Run Code Online (Sandbox Code Playgroud)

ForeignKeyAttribute用于配对导航属性和外键属性.它包含相关导航属性的名称或相关外键属性的名称.


Gat*_*ats 6

您可以使用实体配置.

在实体配置中,将此映射添加到类别实体配置:

HasMany<Product>(x => x.Products).WithRequired().HasForeignKey(x => x.CId);
Run Code Online (Sandbox Code Playgroud)

您只需要在其中一个类上映射它,DbContext就足够聪明地使用它.

有关详细信息,请参阅此博客文章.

编辑为了使用数据注释做到这一点我相信正确的方法如下:

[RelatedTo(RelatedProperty="Products", Key="CId", RelatedKey="CategoryId")]
public virtual Category Category { get; set; }
Run Code Online (Sandbox Code Playgroud)