值相同但名称使用linq不同

时间:2016-06-14 06:49:03

标签: linq linq-query-syntax

一个表列中有两个表是FID .. FID在表'tblRe '中,db中的类型是字符串,而其他表中的列是MID .. MID在表'tblVeh'中并且键入在db中,int两个值都相同但名称不同。我尝试调整,但这显示错误

                string data = "[";
                var re = (from veh in DB.tblVeh
                          join regh in DB.tblRe on 
                          new{MID=veh .MID} equals new {MID=tblRe .FID}
                          where !(veh .VName == "")
                          group veh by veh .VName into g
                          select new
                          {
                              Name = g.Key,
                              cnt = g.Select(t => t.Name).Count()
                          }).ToList();


                   data += re.ToList().Select(x => "['" + x.Name + "'," + x.cnt + "]")
                  .Aggregate((a, b) => a + "," + b);

                  data += "]";

我试试这个

 new{MID=veh .MID} equals new {MID=tblRe .FID}

错误

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

任何解决方案

2 个答案:

答案 0 :(得分:1)

当键具有不同类型时,很难加入。 linq2sql需要能够将您的查询转换为sql语句才能执行它。 我认为最好的解决方案是从db中获取intrest行,然后进行连接。这样就可以使用任何代码,因为它不需要转换为sql。

        //Get the list of items from tblVeh
        var listOfVehs =
            (from veh in DB.tblVeh
             where !(veh.VName == "")
             select veh).ToList();
        //Get all MID from the vehs and convert to string.
        var vehMIDs = listOfVehs.Select(x => x.MID.ToString()).ToList();

        //Get all items from tblRe that matches.
        var listOfRes = (from re in DB.tblRe
                         where vehMIDs.Contains(re.FID)
                         select re).ToList();

        //Do a in code join
        var re = (
            from veh in listOfVehs
            join regh in listOfRes on veh.MID.ToString() equals regh.FID
            group veh by veh.VName into g
            select new
            {
               Name = g.Key,
              cnt = g.Select(t => t.Name).Count()
            }).ToList();

答案 1 :(得分:0)

执行连接时,您需要确保密钥类型匹配。由于您要加入单个属性,因此不需要匿名对象,但类型必须匹配。它更适用于连接字符串,因此将属性转换为字符串。

var query =
    from v in db.tblVeh
    join r in db.tblRe on Convert.ToString(v.MID) equals r.FID
    where v.VName != ""
    group 1 by v.VName into g
    select $"['{g.Key}',{g.Count()}]";
var data = $"[{String.Join(",", query.AsEnumerable())}]";