簡體   English   中英

在實體框架中編寫查詢

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM