我在其中一个实体框架应用程序中运行此代码。我知道必须有比这个代码执行的三个查询更好(更有效)的方式。虽然,我无法完全理解语法。 (我仍然自己学习Entity Framework ..)实体框架查询
有两个表参与。这是一个简单的父母/子女关系。
有一个呼叫表,其中包含有关我们所有呼叫的信息,并且有一个单位表包含分配给每个呼叫的单个序列号(单位)。请注意,这不是一个多对多的关系。单位表可以/将包含重复记录(序列号)!
一个调用在Units表中可以有0-多个子记录。
因此,当呼叫者呼入时,我们的客户代表会输入一个序列号(总是在单位表中创建一个新记录),将其与此呼叫相关联。此时我们填入“通话记录”选项卡。该标签由下面的查询构建。 (搜索单位表并查找与此单位匹配的所有单位,然后返回分配给所有这些单位(记录)的所有呼叫。)
总结。查询的目标是:根据呼叫ID,在数据库中查找任何其他呼叫,这些呼叫也与分配给此呼叫的任何序列号绑定。
考虑到实体框架在名为“Categories”的tblCall表中创建了一个导航,而在名为“Call”的tblCategory表中,必须有更好/更有效的方式来编写此查询。我真的很想重构它。 :)
下面是现有的查询:
//First, get all the Serial Numbers assigned to this Call.
var serials = from units in context.tblUnits
where units.callID == callID
select units.unitSerialNumber;
List<string> serialsList = serials.ToList<string>();
//Get all of the Call IDs that are assigned to any of the serial numbers from the list above
var callIDs = from units in context.tblUnits
where serialsList.Contains(units.unitSerialNumber)
select units.callID;
List<int> callIDList = callIDs.ToList<int>();
//Return all of the calls that are in the callID list from above
var data = from calls in context.tblCalls
where callIDList.Contains(calls.callID)
select calls;
result = data.ToList<tblCall>();
任何意见得多apprecaited!
感谢您的帮助Daniel。下面是最终的查询:
var query = (from u1 in context.tblUnits
join u2 in context.tblUnits on u1.unitSerialNumber equals u2.unitSerialNumber
join c in context.tblCalls on u2.callID equals c.callID
where u1.callID == callID
select c).Distinct();
result = query.ToList();
我想试试。谢谢。 我想也可能有一些方法来利用每个表上的导航属性。 (例如tblCalls有一个“Units”导航属性,而tblUnits有一个“Call”导航属性...) – Shayne 2010-08-06 18:10:37
在这种情况下,你可能会消除第二次连接(到tblCalls)和'select u2.Call'。 – 2010-08-06 18:24:24
那么,你认为这会起作用吗? var query = from u1 in context.tblUnits join u2 in context.tblUnits on u1.unitSerialNumber equals u2.unitSerialNumber where u1.callID == 1 select u2.Call; var result = query.ToList(); “u1.callID == 1”的用途是什么? – Shayne 2010-08-09 13:06:30