我正在尝试加入两列,但其中一列是Varchar
,另一列是NVarchar
我的LINQ代码:
private BrattleHubEntities officeInfo = new BrattleHubEntities();
private BrattlecubesEntities empInfo = new BrattlecubesEntities();
var employeeOfficeInfo = from t1 in officeInfo.DimOffices
join t2 in empInfo on t1.OfficeCode equals t2.EmployeeOffice
select new { t1.OfficeCode, t1.MainPhone, t1.MainFax }
这会显示错误消息:
Join子句中某个表达式的类型不正确。调用“加入”时类型推断失败。
从研究中我了解到这是因为empInfo.EmployeeOffice
是NVarchar(30)
而officeInfo.OfficeCode
是Varchar(20)
如何投射这些字符串以执行加入?
提前谢谢
更新 即使使用以下代码,我也收到同样的错误
var employeeOfficeInfo = from t1 in officeInfo.DimOffices
join t2 in empInfo on 1 equals 1
select new { t1.OfficeCode, t1.MainPhone, t1.MainFax }
答案 0 :(得分:0)
您可以使用嵌套linq查询返回的anon对象在子查询中显式转换两种类型的值,然后连接两个子查询的结果以返回所需的对象。问题在技术上不是一个SQL服务器,它是一个.NET服务器。 LINQ不知道如何将映射对象的这两种数据类型连接在一起。所以你需要明确地告诉链接这两种类型是如何相关的。或者,您可以使用tsql执行此查询并将varchar转换为nvarchar。 JOIN t2 ON (CONVERT(NVARCHAR(30), t1.OfficeCode, 0) = t2.EmployeeOffice)
答案 1 :(得分:0)
我解决了这个问题,对不起,我排除了罪魁祸首。
原始代码(完整)
private BrattleHubEntities officeInfo = new BrattleHubEntities();
private BrattlecubesEntities empInfo = new BrattlecubesEntities();
// GET: DimOffices
public ActionResult Index()
{
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string currentUserLogin = currentUser.Substring(10);
var employee = from e in empInfo.DimEmployees//Method 1 to pull current user
select e;
employee = employee.Where(e => e.UserLogin.Contains(currentUser) && e.EmployeeOffice.Contains("BOS"));
var employeeOfficeInfo = from t1 in officeInfo.DimOffices
join t2 in empInfo on t1.OfficeCode equals t2.EmployeeOffice
select new { t1.OfficeCode, t1.MainPhone, t1.MainFax };
return View(employeeOfficeInfo);
}
运行代码
private BrattleHubEntities officeInfo = new BrattleHubEntities();
private BrattlecubesEntities empInfo = new BrattlecubesEntities();
// GET: DimOffices
public ActionResult Index()
{
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string currentUserLogin = currentUser.Substring(10);
var employee = from e in empInfo.DimEmployees//Method 1 to pull current user
select e;
employee = employee.Where(e => e.UserLogin.Contains(currentUser));
var employeeOfficeInfo = from t1 in officeInfo.DimOffices
join t2 in employee on t1.OfficeCode equals t2.EmployeeOffice
select new { t1.OfficeCode, t1.MainPhone, t1.MainFax };
return View(employeeOfficeInfo);
}
问题在于我已经在EmpInfo上生成了一个数据集并重命名了它。如果我注释掉var员工逻辑,我得到了我发布的问题,我不知道为什么EmpInfo需要LINQ选择