Easier to show by example — I’m using code-first to construct a database. I have the following classes:
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
public List<Post> Posts { get; set; }
public string BlogCode
{
get
{
return Title.Substring(0, 1) + ":" + AuthorName.Substring(0, 1);
}
}
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public virtual Blog Blog { get; set; }
}
I don’t understand why Post needs a public virtual Blog Blog. Does it act as a foreign key in the database to link back to the Blog? It seems like if that were the case you would use the Blog Id.
It does allow the two tables to be related and places a foreign key on
Postrelating toBlog.Having
public virtual Blog Blog { get; set; }allows you to reference theBlogobject from aPostobject and then get access to all the properties of theBlog. E.g.myPost.Blog.IdIf it usedpublic virtual int BlogId { get; set; }, you would not be able to do this sinceBlogIdwould just be anintvalue.If your domain objects are lazy loaded,
myPost.Blogwill not actually be hydrated with data from the database (i.e. no call to theBlogtable) until that property is used. As soon as it is used, Entity Framework will make the database call for you and hydrate the object with data from theBlogtable. This is part of the beauty of using an ORM… it allows you to focus on the code while it takes care of the database operations.