实体框架中的外键4.1

时间:2011-03-27 11:40:43

标签: .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; }
} 

请建议

2 个答案:

答案 0 :(得分: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; }
}

或者:

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

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

答案 1 :(得分:6)

您可以使用实体配置。

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

HasMany<Product>(x => x.Products).WithRequired().HasForeignKey(x => x.CId);

您只需将它映射到您的某个类上,DbContext就足够聪明地使用它。

有关详细信息,请参阅此blog post

编辑为了使用数据注释,我认为正确的方法如下:

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