我正在尝试解决问题:
我不知道如何从我的查询中访问cnt值,或者如何重写它以便在我的项目中使用
Select * from samples as s INNER JOIN (SELECT sampleId, SUM(quantity) cnt FROM locationsamples GROUP BY sampleID) sl ON sl.sampleID=s.SampleId;
上面的查询为我提供了所需的信息。
如何从我的控制器访问Summed cnt值,以便我可以在视图中阅读它?
public class samples
{
[Key]
public int SampleId { get; set; }
//many to many relationship for locations (one sample can be in many locations, with a quantity in each)
public virtual ICollection<locationsamples> locationsamples { get; set;
}
public class locationsamples
{
public int locationsamplesID { get; set; }
public int locationID { get; set; }
public virtual location location { get; set; }
public int sampleID { get; set; }
public virtual sample sample { get; set; }
public int quantity { get; set; }
}
答案 0 :(得分:0)
您可以在locationamples上分组,然后选择您需要的聚合字段。你想要的是这样的:
var list = dbContext.locationsamples
.GroupBy(e => e.sampleID)
.Select(group => new
{
SampleId = group.key,
Cnt = group.Sum(c => c.quantity),
}).ToList();