ASP.NET CORE 1.0 Repository Loading related data EF CORE

entity-framework entity-framework-core

Question

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.

1
0
7/14/2016 11:29:48 PM

Accepted Answer

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.

0
8/11/2016 9:07:23 AM

Popular Answer

you need to add the following line to avoid circular reference

services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow