在“包含在EF Core中”中选择

时间:2018-08-26 09:49:30

标签: entity-framework asp.net-core entity-framework-core

我有一个看起来像这样的实体(为简洁起见部分删除,它包含许多其他属性):

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>();
}

TenderCircles属性用于提供与另一个称为Circle的实体的多对多关系。 TenderCircle实体看起来像这样:

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; }
}

现在,我正在执行以下查询(为了简洁起见,部分删除了该查询,通常它包含许多其他IncludeThenInclude语句):

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

但是,它根本不起作用。我想要实现的是,我只想从TenderId获取CircleIdTenderCircle属性,而忽略实际的TenderCircle对象。知道如何在 EF Core 中实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

编写查询,如下所示:

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();

然后TenderViewModel如下:

public class TenderViewModel
{
   public int Id { get; set; }
   public AppUser Creator { get; set; }
   public List<TenderCircle> TenderCircles { get; set; }
}