1

我有一个名为 TestNotifications 的表,它有一个 CompanyID 和一个 TestCompanyID。这些 ID 链接到具有 companyName 列的 Companies 表。我需要获取公司的 companyName 和 testCompany。下面的代码不起作用,我得到一个不能隐式转换的错误。任何帮助表示赞赏。

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?)
4

3 回答 3

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
    };
于 2012-06-13T16:22:08.177 回答
0

I suspect the issue lies in how you declared testNotifications. If you did something like the following, you would see that error:

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 
    }; 

You would also get this same issue if you declared the testNotifications at the start and then continued with the query later on because you are trying to change the type of the value from the known type to an anonymous type.:

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 
        }; 

Since you are projecting an anonymous type, you need to use type inference and not explicitly declare the variable:

var testNotifications = from .. select ..;
于 2012-06-13T17:33:59.510 回答
0

查看您的加入条件是否属于相同类型 - IE 是 t.CompanyID 和 int 和 c.CompanyID。

于 2012-06-13T16:18:21.063 回答