[英]Write query in Entity Framework
我有一个在 SQL Server Management Studio 中成功运行的查询,它返回屏幕截图中显示的表值
我使用的查询是:
SELECT tcoid, COUNT(*) ownleasetank
FROM TankProfile
WHERE ownleasetank = 3
GROUP BY tcoid
现在,我正在使用 Entity Framework 来简化示例项目中的操作。
我使用此方法将表值作为数组 object 返回:
public async Task<Object> GetLeaseInformationPrincipal()
{
ISOTMSEntities context = new ISOTMSEntities();
var testleaseinfo = from d in context.TankProfiles
join f in context.TankOperators
on d.tcoid equals f.tcoId
where (d.ownleasetank == 3)
select new { f.tcoName, d.ownleasetank } into x
group x by new { x.tcoName } into g
select new
{
tconame = g.Key.tcoName,
ownleasetank = g.Select(x => x.ownleasetank).Count()
};
return testleaseinfo.ToList();
}
但它不能正常工作。 我还尝试了其他方法,当我在实体框架中使用 where 和 groupby 方法时,它对我来说不能正常工作。
有人知道解决方案吗?
使用 LINQ 方法非常简单:
context.TankProfiles
.Where(t => t.ownleasetank = 3)
.GroupBy(t => t.tcoid)
.Select(g => new {g.Key, g.Count()})
.ToArray();
我不知道为什么在您的 C# 版本的查询中您有这样的操作,例如join
,而您的 SQL 查询非常简单。 你必须重新考虑:)
var c = from t in context.TankProfile
where t.ownleasetank == 3
group t by t.tcoid into g
select new { tcoid=g.Key, ownleasetank=g.Select(x => x.ownleasetank).Count() };
return c.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.