我有一个表名TestNotifications,它有一个CompanyID和一个TestCompanyID。这些ID链接到具有companyName列的Companies表。我需要获得公司和testCompany的companyName。下面的代码不起作用,我得到一个不能隐式转换错误。任何帮助表示赞赏。
testNotifications = from t in db.CT_TestNotifications
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
join tc in db.CT_Companies on t.TestCompanyID equals tc.CompanyID
select new
{
t.TestNotificationID,
c.CompanyName,
//tc.CompanyName
TestCompanyName = tc.CompanyName
};
这是错误:
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to
'System.Linq.IQueryable<CT_TestNotification>'. An explicit conversion exists
(are you missing a cast?)
答案 0 :(得分:3)
您投射的是匿名类型,但testNotifications
期望CT_TestNotification
。
尝试在CT_TestNotification
中创建select
的实例:
testNotifications = from t in db.CT_TestNotifications
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
join tc in db.CT_Companies on t.TestCompanyID equals tc.CompanyID
select new CT_TestNotification // Here's the major difference
{
PropName = t.TestNotificationID, // PropName must be changed to the
PropName = c.CompanyName, // properties of your actual class
//tc.CompanyName
TestCompanyName = tc.CompanyName
};
答案 1 :(得分:0)
查看您的条件连接是否属于相同类型 - IE是t.CompanyID是int和c.CompanyID。
答案 2 :(得分:0)
我怀疑问题在于您如何声明testNotifications。如果你做了类似下面的事情,你会看到错误:
IQueryable<CT_TestNotifications> testNotifications;
testNotifications = from t in db.CT_TestNotifications
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
join tc in db.CT_Companies on t.TestCompanyID equals tc.CompanyID
select new
{
t.TestNotificationID,
c.CompanyName,
//tc.CompanyName
TestCompanyName = tc.CompanyName
};
如果您在开始时声明了testNotifications,然后继续查询,那么您也会遇到同样的问题,因为您尝试将值的类型从已知类型更改为匿名类型。:
var testNotifications = db.CT_TestNotifications;
testNotifications = from t in testNotifications
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
join tc in db.CT_Companies on t.TestCompanyID equals tc.CompanyID
select new
{
t.TestNotificationID,
c.CompanyName,
//tc.CompanyName
TestCompanyName = tc.CompanyName
};
由于您要投射匿名类型,因此需要使用类型推断而不是显式声明变量:
var testNotifications = from .. select ..;