【问题标题】:Write query in Entity Framework在实体框架中编写查询
【发布时间】:2020-11-09 07:30:18
【问题描述】:

我有一个在 SQL Server Management Studio 中成功运行的查询,它返回屏幕截图中显示的表值

我使用的查询是:

SELECT tcoid, COUNT(*) ownleasetank 
FROM TankProfile
WHERE ownleasetank = 3  
GROUP BY tcoid

现在我正在使用 Entity Framework 来简化示例项目中的操作。

我使用这种方法将表值作为数组对象返回:

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 中有一个额外的连接结构,但它在您提供的 sql 查询中不存在
  • 什么工作不正常。了解更多

标签: c# .net sql-server entity-framework entity-framework-6


【解决方案1】:

使用 LINQ 方法非常简单:

context.TankProfiles
    .Where(t => t.ownleasetank = 3)
    .GroupBy(t => t.tcoid)
    .Select(g => new {g.Key, g.Count()})
    .ToArray();

我不知道为什么在你的 C# 版本的查询中有 join 这样的操作,而你的 SQL 查询非常简单。你必须重新考虑:)

【讨论】:

    【解决方案2】:
    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多