Create a Foreign Key relationship using Code First Entity Framework and asp.net MVC4 | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Create a Foreign Key relationship using Code First Entity Framework and asp.net MVC4

Saturday

Entity Framework Code First: Add a Foreign Key relationship in asp.net MVC 4:

When building an single page application in MVC4 using Entity Framework Code First you might run into the following exception:

Unable to retrieve association information for association 'Models.Product_Parent'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information.

This is due to the way you've defined the relation ships in the dbContext. Lets say me have a dbContextcontaining products which can have child products, you would write the following code:

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Product Parent { get; set; }
}
public class ProductContext : DbContext
{
    public DbSet<product> Products { get; set; }
}


This should be enough to let EF know there is a relationship in there, but sadly it's not. We can solving this by following way:

we can create an extra property ParentId give this a ForeighKeyAttribute that links it to the Parent property.

[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Product Parent { get; set; }


0 comments:

Post a Comment

Share your thoughts here...

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets