ef核心从tableA中选择记录,并在tableB中匹配字段

时间:2017-12-06 08:49:27

标签: entity-framework linq ef-core-2.0

我正在尝试将查询从原始sql转换为EF Core 2中的linq语句

查询是这样的

SELECT * FROM TableA
WHERE FieldA = ConditionA
AND FieldB IN (SELECT FieldC FROM TableB WHERE FieldD = ConditionB)

FieldA和FieldB来自TableA,FieldC和FieldD来自TableB

我需要TableA中的所有字段,而TableB中没有字段返回,所以它应该像

return Context.TableA
    .Where(x => x.FieldA == ConditionA)
    .[ some code here ]
    .ToList()

我目前的解决方案是获取两个不同的结果集并将它们加入代码中,类似这样的

var listA = Context.TableA
    .Where(x => x.FieldA == ConditionA).ToList();
var listB = Context.TableB
    .Where(x => x.FieldD == ConditionB).Select(x => x.FieldC).ToList();
listA.RemoveAll(x => !listB.Contains(x.FieldB);
return listA;

我希望它有效,我仍然需要对它进行测试,但我正在寻找更好的解决方案(如果有的话)

2 个答案:

答案 0 :(得分:1)

您可以在查询中使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="box"> <div class="top"> About </div> <div class="bottom"> ABout Me </div> </div> <div class="box"> <div class="top"> Service </div> <div class="bottom"> all Services </div> </div> <div class="box"> <div class="top"> Clients </div> <div class="bottom"> All Clients </div> </div> </div>函数,如下所示:

Contains

答案 1 :(得分:0)

这是一个需要应用的简单连接 -

var result = (from a in Context.TableA.Where(x => x.FieldA == ConditionA )
         join b in Context.TableB.Where(x => x.FieldD == ConditionB) on a.FieldB equals b.FieldC
         select new {a}
         ).ToList();