一个表列中有两个表是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'.
任何解决方案
当键具有不同的类型时,将很难加入。 LINQ2SQL 需要能够将查询转换为 SQL 语句才能执行它。我认为最好的解决方案是从数据库中获取 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();
执行联接时,需要确保密钥类型匹配。 由于要加入单个属性,因此不需要匿名对象,但类型必须匹配。它更适合连接字符串,因此将属性转换为字符串。
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())}]";