I have the following classes that I am using with EF5
public class Question
{
public Question()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
...
...
public string Title { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
Can someone tell me why there is a need for the property:
public virtual Question Question { get; set; }
If I never intend to do automatic lazyloading but do intend to sometimes bring that object in with an include then do I need the virtual property like this:
var questions = _questionsRepository.GetAll()
.Include(a => a.Answers);
The reason I am asking is because when used with Web API it is giving me circular reference errors with json.
Without viewing your mapping configuration, there's probably a little bit of assumption on my part, but I suspect you're using Independent Association to define the associative relationships between your entities.
This is a feature of Entity Framework, where the relationships between objects are modelled as references, so you don't actually need foreign key properties to be present on your objects; it does mean that both of your entities will need a to have a navigation property defined, so Entity Framework is able to manage the association. In your case, you are required to have a Question property on your Answers entity.
In later versions of Entity framework (I believe 4 onwards), you can use a different type of association "Foreign key association", which will allow you to form associations using foreign key properties, which should allow you to remove the Question navigation property (which may or may not help you).
There's a much better explanation as the accepted answer here: Code First: Independent associations vs. Foreign key associations?
That said, if your association is working correctly, your problem may be with how you're then using your entities/Web API (which I don't know well enough to comment on).
Good luck =D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With