I have a head and a details model with navigation properties between them. I'd like to get head records with details included. This works fine but the detail records I got doesn't contain all properties I need so I tried to add Include().
EF Core says ICollection<RequestDetail> does not contain a definition for 'Include'
. I have already tried with List<> navigation types and Microsoft.EntityFrameworkCore
and System.Linq
are both in my usings.
My models:
public class RequestHead
{
public string Id { get; set; }
public DateTime CreateDate { get; set; }
public int CreateUserId { get; set; }
[ForeignKey("CreateUserId")]
public User CreateUser { get; set; }
public virtual ICollection<RequestDetail> Details { get; set; }
}
public class RequestDetail
{
[Key]
public int Id { get; set; }
public string RequestHeadId { get; set; }
[ForeignKey("RequestHeadId")]
public RequestHead RequestHead { get; set; }
public DateTime CreateDate { get; set; }
public int CreateUserId { get; set; }
[ForeignKey("CreateUserId")]
public User CreateUser { get; set; }
}
Select:
var requests = (from r in _ctx.RequestHeads
select new RequestDTO {
AcceptDate = r.AcceptDate,
AcceptUser = r.AcceptUser,
AcceptUserId = r.AcceptUserId,
Details = r.Details != null ?
r.Details.Include(x => x.BuyerUser).Select(x => new
RequestDetailDTO(x, x.Attachments.ToArray(), x.Product)).ToArray() : null});
Update#1:
This is not a Json.ReferenceLoopHandling problem. It is already ignored in startup.cs and my problem is that I can't use Include() even in my code not just not having the neccessary properties in the json.
It's like the error suggests: Your property r.Details is an ICollection (a navigation property) and does not expose an .Include() method, which is only available for IQueryables (Extension method). The include path(s) should point from the returned IQueryable to the navigation properties you wish to include, in your case this should be something along the lines of
.Include(x=>x.Details.Select(y=>y.BuyerUser))
If developing on .NET - make sure you are using the System.Data.Entity namespace.
using System.Data.Entity;
If on .NET Core - use Microsoft.EntityFrameworkCore instead.
using Microsoft.EntityFrameworkCore;