代码之家  ›  专栏  ›  技术社区  ›  Shayne

实体框架查询

  •  0
  • Shayne  · 技术社区  · 15 年前

    我在我们的一个实体框架应用程序中遇到了这段代码。我知道必须有比这段代码执行的三个查询更好(更有效)的方法。尽管如此,我还是不能很好地理解语法。(我仍在学习实体框架……)

    有两张桌子。这是一种简单的父子关系。

    有一个调用表,其中包含有关所有调用的信息,还有一个单位表,其中包含分配给每个调用的各个序列号(单位)。注意,这不是一种多对多的关系。单位表可以/将包含重复记录(序列号)!!

    一个调用在Units表中可以有0多个子记录。

    因此,当调用者呼叫时,我们的客户代表输入一个序列号(总是在Units表中创建一个新记录),将其与此呼叫关联。此时,我们将填充一个“通话历史记录”选项卡。此选项卡由下面的查询生成。(搜索Units表并查找与此单元匹配的所有单元,然后返回分配给所有这些单元(记录)的所有调用。)

    总结。查询的目的是:基于calid,在数据库中查找与分配给此调用的任何序列号绑定的任何其他调用。

    考虑到实体框架在名为“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>();
    

    任何建议都会受到重视!

    谢谢你的帮助,丹尼尔。最后一个问题是:

    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();
    
    1 回复  |  直到 15 年前
        1
  •  0
  •   Daniel Pratt    15 年前

    我想你可以用类似这样的查询来替换它:

    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 ?? -1) equals c.callID
            where u1.callID == callID
            select c;
    
    var result = query.ToList();