在实体框架4.1外键实体、框架、外键

由网友(坐观雾漫长安)分享简介:我工作的实体框架4.1,并使用数据注释外键。我想知道我们如何能够定义一个产品和类别之间一对多的关系。我要地图类别。的categoryId与product.cid I am working on Entity Framework 4.1 and using data annotations for foreign ke...

我工作的实体框架4.1,并使用数据注释外键。我想知道我们如何能够定义一个产品和类别之间一对多的关系。我要地图类别。的categoryId与product.cid

I am working on Entity Framework 4.1 and using data annotations for foreign keys. I want to know how can we define one to many relationship between product and categories. I want to map category. 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; }
} 

请提示

推荐答案

这两种方法应该工作:

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

ForeignKeyAttribute is used to pair navigation property and foreign key property. It contains either the name of related navigation property or the name of related foreign key property.

阅读全文

相关推荐

最新文章