Reputation: 441
I have a project that was running with .net core 3.1. After upgrading to .net 5 and entity framework core to 5.0.3, the include is not working anymore.
I have these classes
public class Question
{
[Key]
public Guid Id { get; set; }
public string QuestionCode { get; set; }
[ForeignKey("AnswersId")]
public Answer Answers { get; set; }
}
public class Answer
{
[Key]
public Guid Id { get; set; }
public string Answers { get; set; }
public int Score { get; set; }
}
The relation is defined as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
}
and this simple LINQ:
return _context.Questions
.Include(q => q.Answers)
.FirstOrDefault(s => s.Id == id);
however. the include is not working after the version upgrade. By not working i mean the returned values doesn't include Answers. Main entity only is returned and all the fields in the child are null.
Upvotes: 9
Views: 14592
Reputation: 389
In my case I had a wrong using while still compiling and no runtime error - nothing to do with an upgrade.
Wrong:
using System.Data.Entity;
Fixed with:
using Microsoft.EntityFrameworkCore;
Upvotes: 20
Reputation: 6607
I am not a 100% sure if this is the issue, since you said that it was working fine previously, but it might be that your relationship is not configured properly in OnModelCreating
since it is lacking a call to either WithOne
or WithMany
to be correct.
From docs:
After calling this method, you should chain a call to WithMany(String) or WithOne(String) to fully configure the relationship. Calling just this method without the chained call will not produce a valid relationship.
There is a breaking change in EF 5 related to the semantics of a required nagivation property from the principal (Question) to the dependant (Answer) which might be the explanation for the wrong behavior after upgrading the library.
So let's give a shot to this... try to configure your relationship like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
.WithOne()
.IsRequired();
}
Upvotes: 8