I am working on creating a ASP.NET Core 1.0 and I have created the same application in RC1. I am having an issue with querying related table data with EF Core.
Previously I used EF7 and everything worked just fine regardless if there is data in the field or not. My issue is that it is not returning a collection of all the records when I use .Include. I created my model with my nuget console using the sample on https://docs.efproject.net/en/latest/querying/related-data.html:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
And got this model:
public partial class Complaint
{
public Complaint()
{
Checklist = new HashSet<Checklist>();
Clnotes = new HashSet<Clnotes>();
}
public int CompId { get; set; }
public string FileNum { get; set; }
public DateTime? ReceivedDt { get; set; }
public DateTime? CompletedDt { get; set; }
public virtual ICollection<Checklist> Checklist { get; set; }
public virtual ICollection<Clnotes> Clnotes { get; set; }
}
My Repository for GetAll():
public IEnumerable<Complaint> GetAll()
{
try
{
return _context.Complaint
//.Include(t => t.Checklist)
//.Include(cl => cl.Clnotes)
.ToList();
}
catch (Exception ex)
{
_logger.LogError("Could not get complaint with checklist", ex);
return null;
}
}
Question
Why is that when I was using EF7 including related tables, included the data for every single record in the database. For EF Core, when I include the checklist or clnotes table, only one records shows ? When I don't include the related table, all the Complaints show up.
I had the same problem. I don't know why it works like this, but selecting the fields after including solved it for me. Try something like this:
return _context.Complaint
.Include(t => t.Checklist)
//.Include(cl => cl.Clnotes)
.Select(c => new {
c.CompId, c.FileNum, c.Checklist, // c.Clnotes
)
.ToList();
You will probablly need to change the method type from IEnumerable to something other, like IActionResult.
you need to add the following line to avoid circular reference
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});