Foreign keys in entity framework 4.1

DotnetSparrow picture DotnetSparrow · Mar 27, 2011 · Viewed 18k times · Source

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

Answer

Ladislav Mrnka picture Ladislav Mrnka · Mar 27, 2011

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.