Select inside Include in EF Core

asp.net-core entity-framework entity-framework-core

Question

I have an entity that looks like this (partially removed for brevity, it includes many other properties):

public class Tender
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string CreatorId { get; set; }
    [ForeignKey("CreatorId")]
    public virtual AppUser Creator { get; set; }
    public ICollection<TenderCircle> TenderCircles { get; set; } = new List<TenderCircle>();
}

The TenderCircles property is used to provide a many-to-many relationship with another entity called Circle. TenderCircle entity looks like this:

public class TenderCircle
{
    public int TenderId { get; set; }
    [ForeignKey("TenderId")]
    public Tender Tender { get; set; }
    public int CircleId { get; set; }
    [ForeignKey("CircleId")]
    public Circle Circle { get; set; }
}

Now, I'm doing the following query (partially removed for brevity, normally it includes many other Include and ThenInclude statements):

return _context.Tenders
               .Include(t => t.Creator)
               .Include(t => t.TenderCircles.Select(tc => new { CirlceId = tc.CircleId, TenderId = tc.TenderId }))
               .ToList();

But, it simply doesn't work. What I want to achieve is that I only want to get the TenderId and CircleId properties from TenderCircle and ignore the actual Tender and Circle objects. Any idea how to achieve this in EF Core?

1
1
8/26/2018 10:58:58 AM

Accepted Answer

Write your query as follows:

return _context.Tenders.Select(t => new TenderViewModel
                       {
                          Id = t.Id,
                          Creator = t.Creator,
                          TenderCircles = t.TenderCircles.Select(tc => new TenderCircle { CirlceId =  tc.CircleId, TenderId = tc.TenderId }).ToList();
                       }).ToList();

Then TenderViewModel as follows:

public class TenderViewModel
{
   public int Id { get; set; }
   public AppUser Creator { get; set; }
   public List<TenderCircle> TenderCircles { get; set; }
}
0
8/26/2018 11:10:02 AM


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