The Code Gorilla
Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Monday, 18 March 2013

Entity framework, why the virtual on references?

I've been perplexed for a little while about the entity framework when using code first.

Consider the following:

A multiple choice database, one question with multiple answers:

public class Answer
{
    public int AnswerID { get; set; }
    public int QuestionID { get; set; }

    public string Text { get; set; }
    public bool IsCorrect { get; set; }

    public virtual Question Question { get; set; }
}

public class Question
{
    public int QuestionID {get;set;}
    public string Text { get; set; }

    public virtual ICollection<Answer> Answers { get; set; }
}

public class MultiChoiceContext : DbContext, IDataModel
{
    public DbSet<Question> Questions { get; set; }
}

The question that's always been in my mind is why the virtual on the external reference on Question (line 9) and ICollection (line 17), I've seen lots of examples on the internet that do and do not have the virtual keyword and until recently I've never understood why. So I'm here to enlighten you.