Foreign keys in entity framework 4.1

2019-01-11 10:22发布

问题:

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

Please suggest

回答1:

Both these approaches should work:

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

Or:

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 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.



回答2:

You use entityconfigurations for this.

In the entityconfiguration, add this mapping to the category entityconfiguration:

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

You only need to map it on one of your classes and DbContext is clever enough to use it.

See this blog post for more info.

EDIT To do this using data annotations I believe the correct approach is as follows:

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