2

一个表列中有两个表是 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'.

任何解决方案

4

2 回答 2

1

当密钥具有不同的类型时,将很难加入。linq2sql 需要能够将您的查询转换为 sql 语句才能执行它。我认为最好的解决方案是从数据库中获取感兴趣的行,然后进行连接。这样任何代码都可以使用,因为它不需要转换成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();
于 2016-06-14T07:58:41.173 回答
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())}]";
于 2016-06-23T02:52:24.857 回答