23

我正在研究 Entity Framework 4.1 并为外键使用数据注释。我想知道我们如何定义产品和类别之间的一对多关系。我想映射类别。categoryId 和 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; }
} 

请建议

4

2 回答 2

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用于配对导航属性和外键属性。它包含相关导航属性的名称或相关外键属性的名称。

于 2011-03-27T11:56:01.590 回答
6

您为此使用实体配置。

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

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

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

有关更多信息,请参阅此博客文章

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

[RelatedTo(RelatedProperty="Products", Key="CId", RelatedKey="CategoryId")]
public virtual Category Category { get; set; }
于 2011-03-27T11:46:01.353 回答