2014-11-05 54 views
0

我有我自己的SQL查詢轉換SQL查詢LINQ查詢,但只有選擇特定值返回

SELECT follow_up_date, MAX(last_contact_date) AS last_contact_date 
FROM db_accounts_last_contacts p 
GROUP BY p.account_id 

我已經試過

var queryTest = context.db_accounts_last_contacts.SqlQuery(@"SELECT follow_up_date, MAX(last_contact_date) AS last_contact_date 
FROM db_accounts_last_contacts p 
GROUP BY p.account_id"); 

,但我得到這個錯誤。

The data reader is incompatible with the specified 'dbModel.db_accounts_last_contacts'. A member of the type, 'id', does not have a corresponding column in the data reader with the same name. 

我不想退出時,所有的信息,因爲這表也許以後更新的路線,我只是想拔出這兩列

+2

該SQL查詢是否工作?您不需要在group by子句中使用follow_up_date,因爲它不在聚合函數中? – juharr 2014-11-05 16:52:30

回答

2

我認爲你試圖訪問數據庫表與表本身相關聯。 並且您在p變量前缺少「AS」。 嘗試以下操作:

var queryTest = context.ExecuteSqlCommand(@"SELECT follow_up_date, MAX(last_contact_date) AS ast_contact_date 
             FROM db_accounts_last_contacts AS p 
             GROUP BY p.account_id, follow_up_date, ast_contact_date "); 

讓我知道如何去。

P.S. 我真的推薦使用EntityFramework,因爲它將您的視點從SQL'ish轉換爲C#pov。這通常更容易理解。

+0

我已經創建了自己的視圖,但是實體框架現在抱怨「沒有主鍵」你怎麼在視圖中設置主鍵這裏是我的視圖「select'p'.'account_id' AS' AS'last_contact_date','p'.'id' AS'''''''''communique''''communique_accounts_last_contacts'''''''''''''' p'group by p'.account_id'「另外,你不能在上下文 – Canvas 2014-11-05 17:31:22

+0

1st上調用SqlQuery,因爲@juharr在Comment to you問題中說,首先你必須在Group By子句中有follow_up_date。 SELECT中的任何元素都必須按Grouped。第二,不要在表格中設置主鍵的壞習慣。第三,爲了強制實體框架使用列作爲主鍵,使用ISNULL。 – Noxymon 2014-11-06 12:12:04

+0

嗯,我已經解決了我的問題,使用視圖,上面的工作,所以我會打勾它,但是我使用視圖的原因是,我之前沒有使用過視圖,所以感覺很好:) – Canvas 2014-11-07 09:38:57