The previous EF Framework Step by step (7)-code first dataannotations (1) describes the use of data characterization within the entity to describe the relationship to the table. This article will use DataAnnotations to describe the relationship between entities.
ForeignKey
Code first automatically establishes the relationships between entities, such as those described in the EF framework Step by Step (3)-code-first in this essay.
public partial class Bloguser
{
public int Bloguserid {get; set;}
public string Blogname {get; set;}
Public virtual icollection<post> Posts {get; set;}
}
public partial class Post
{
public int PostID {get; set;}
public string Posttitle {get; set;}
public int Bloguserid {get; set;}
Public virtual Bloguser Bloguser {get; set;}
}
In this code, the Codefirst method, when generating data, finds the Bloguserid attribute in the post entity (that is, the primary key of the Bloguser entity), and when found, it is associated with the Bloguser entity. If not found, he will automatically create a column, named Bloguser.bloguserid, as the associated property with the Bloguser entity.
Describe the code and modify the code above to:
public partial class Bloguser
{
public int Bloguserid {get; set;}
public string Blogname {get; set;}
Public virtual icollection<post> Posts {get; set;}
}
public partial class Post
{
public int PostID {get; set;}
public string Posttitle {get; set;}
Expect to use this as a foreign key association
public int BlogId {get; set;}
Public virtual Bloguser Bloguser {get; set;}
}
But the actual generated data table
At this point, it can be seen that the Codefirst method, and not as we have envisioned, to blogID as a foreign key, to complete this idea, need to use foreignkey characteristics, the code is modified as follows
public partial class Post
{
public int PostID {get; set;}
public string Posttitle {get; set;}
Expect to use this as a foreign key association
public int BlogId {get; set;}
[ForeignKey ("BlogId")]
Public virtual Bloguser Bloguser {get; set;}
}
EF Framework Step by step (7)-code first DataAnnotations (2)