Foreign keys in entity framework 4.1

*爱你&永不变心* 提交于 2019-11-26 16:27:04

问题


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


来源:https://stackoverflow.com/questions/5448979/foreign-keys-in-entity-framework-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!