如何将以下SQL语句转换为LINQ方法语法



我正在寻求使用EF6将以下SQL语句转换为LINQ的帮助。我似乎一直在研究不同的例子,但没有发现任何有效的例子。我看过linqer(没有成功(我看过linqpad(它不会将sql转换为linq(

下面的查询以SQL格式返回了我想要的内容,目标是基于内部分组返回表的所有列(将分组用作DISTINCT查询(,使用Group的WHERE子句将记录集筛选为所需内容,并在[CdrCallId]上加入内部分组仅返回[CdrCallId匹配的记录。

SELECT ct1.StartTime, ct1.CdrCallID, ct1.CallingNumberId, ct1.CalledNumberId, ct1.ThreadSequence
FROM CallTransactions as ct1
join (select CdrCallID
from CallTransactions as ct2 
WHERE [StartTime] >= '10/1/2020 00:00:00 AM' AND [StartTime] <= '03/31/2021 00:00:00 AM' AND [CalledNumberId] = '1670589' OR [CallingNumberId] = '1670589' OR [DestinationNumberId] = '1670589' OR [TransferringNumberId] = '1670589' OR [KeyPartyNumberId] = '1670589'
group by ct2.CdrCallID) ct2
on ct1.CdrCallID = ct2.CdrCallID
CallingNumberId165862599536816705891658625789001667952704239167058970423916679527042391663834167058970423916638471670589497922
开始时间CdrCallID调用的编号Id线程序列
2020-11-02 12:49:34.007995368-307-637518839290191670589
2021-02-19 14:38:54.60078900-050-63751893781085
2020年10月27日09:58:15.007704239-301-637518833921471663834
2020年10月27日09:58:15.007704239-301-637518833921471663834
2020年10月27日09:57:14.007704239-301-637518833921471663834
2020年10月27日09:57:59.000704239-301-63751883392147
2020-11-02 10:15:06.007497923-307-6375183688115

我认为您的SQL中有一些缺陷,实际上应该是这样的:

SELECT ct1.StartTime, ct1.CdrCallID, ct1.CallingNumberId, ct1.CalledNumberId, ct1.ThreadSequence 
FROM CallTransactions as ct1 
where exists 
(select *
from CallTransactions as ct2 
WHERE ct1.CdrCallID = ct2.CdrCallID and 
(([StartTime] >= '20201001' AND [StartTime] <= '20210331') AND 
([CalledNumberId] = '1670589' OR 
[CallingNumberId] = '1670589' OR 
[DestinationNumberId] = '1670589' OR 
[TransferringNumberId] = '1670589' OR 
[KeyPartyNumberId] = '1670589'));

在Linq,这将是:

var start = new DateTime(2020,10,1);
var end = new DateTime(2021,4,1);
var numberId = "1670589";
var callIDs = ctx.CallTransactions
.Where(x => x.StartTime >= start && x.StartTime < end && 
(x.CalledNumberId == numberId ||
x.CallingNumberId == numberId ||
x.DestinationNumberId == numberId ||
x.TransferringNumberId == numberId ||
x.KeyPartNumberId == numberId))
.Select(x => x.CdrCallId);
var result = ctx.CallTransactions.Where(x => callIDs.Any(ci => ci.CdrCallId == x.CdrCallId)
.Select(ct1 => new {ct1.StartTime, ct1.CdrCallID, ct1.CallingNumberId, ct1.CalledNumberId, ct1.ThreadSequence});

附言:你真的不需要把所有东西都转换成EF Linq。您也可以从Linq调用原始SQL。

IQueryable<CallTransactions> items;
var start=new DateTime(2021,1,10);
var due=new DateTime(2021,3,31);
var result=items.Where(a=>a.StartTime>=start && a.StartTime<=due)
.Where(a=>a.CalledNumberId = '1670589' || 
a.CallingNumberId = 1670589 || 
a.DestinationNumberId = 1670589 || 
a.TransferringNumberId = 1670589 ||
a.KeyPartyNumberId = '1670589')
.Select(a=>new {
a.StartTime, 
a.CdrCallID, 
a.CallingNumberId, 
a.CalledNumberId, 
a.ThreadSequence
});

我认为这不需要联接,一旦过滤了集合,就可以获得所有必需的行。

最新更新