我有一个看起来像这样的实体(为简洁起见部分删除,它包含许多其他属性):
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; }
}
现在,我正在执行以下查询(为了简洁起见,部分删除了该查询,通常它包含许多其他Include
和ThenInclude
语句):
return _context.Tenders
.Include(t => t.Creator)
.Include(t => t.TenderCircles.Select(tc => new { CirlceId = tc.CircleId, TenderId = tc.TenderId }))
.ToList();
但是,它根本不起作用。我想要实现的是,我只想从TenderId
获取CircleId
和TenderCircle
属性,而忽略实际的Tender
和Circle
对象。知道如何在 EF Core 中实现这一目标吗?
答案 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; }
}