Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Entity Framework classes need a virtual member of an unrelated class

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.

like image 400
Nick Brown Avatar asked Feb 21 '23 00:02

Nick Brown


1 Answers

It does allow the two tables to be related and places a foreign key on Post relating to Blog.

Having public virtual Blog Blog { get; set; } allows you to reference the Blog object from a Post object and then get access to all the properties of the Blog. E.g. myPost.Blog.Id If it used public virtual int BlogId { get; set; }, you would not be able to do this since BlogId would just be an int value.

If your domain objects are lazy loaded, myPost.Blog will not actually be hydrated with data from the database (i.e. no call to the Blog table) 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 the Blog table. 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.

like image 65
Kevin Aenmey Avatar answered Feb 24 '23 04:02

Kevin Aenmey