2013-10-21 58 views
2

我想通過EF linq查詢從域對象收集一個值。但我得到一個錯誤,請問可以幫我糾正一下。實體框架中的Linq查詢錯誤

public String[] ReturnPatientIDs(int CounsellingRoomID) 
{ 

    var messageObject = this.context.CounsellingMessages.Where(c => c.CounsellingRoomID == CounsellingRoomID).Distinct(); 

    String[] PatientIDs = new String[messageObject.Count()]; 

    for (int k = 0; k < PatientIDs.Length; k++) 
    { 
     PatientIDs[k] = messageObject.ElementAt(k).Chatname; 
    } 

    return PatientIDs; 
} 

LINQ to Entities does not recognize the method 'Me.Domain.General.CounsellingMessage ElementAt[CounsellingMessage](System.Linq.IQueryable`1[Me.Domain.General.CounsellingMessage], Int32)' method, and this method cannot be translated into a store expression.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NotSupportedException: LINQ to Entities does not recognize the method 'MedicalApp.Domain.General.CounsellingMessage ElementAt[CounsellingMessage](System.Linq.IQueryable`1[MedicalApp.Domain.General.CounsellingMessage], Int32)' method, and this method cannot be translated into a store expression.

Source Error:

Line 43:    for (int k = 0; k < PatientIDs.Length; k++) 
Line 44:    { 
Line 45:     PatientIDs[k] = messageObject.ElementAt(k).Chatname; 
Line 46:    } 
Line 47: 
+0

嘗試更換此PatientIDs [K] = messageObject.ElementAt(k)的.Chatname;這個PatientIDs [k] = messageObject.ToList()[k] .Chatname; – jannagy02

回答

2

ElementAt方法不被支持。在你調用Count()ElementAt()之前,messageObject查詢不會被執行,並且這些查詢將被視爲LINQ to Entity查詢。

for循環所採取的動作可以通過添加Select語句中軋製成的LINQ查詢:

public String[] ReturnPatientIDs(int CounsellingRoomID) 
{ 
    var query = this.context.CounsellingMessages 
        .Where(c => c.CounsellingRoomID == CounsellingRoomID) 
        .Select(c => c.Chatname) 
        .Distinct(); 

    return query.ToArray(); 
} 
+2

把'Select'放在'Distinct'之前可以改變結果(在原始代碼中,「Distinct」是在整個對象上完成的,不在你的一個屬性上)。雖然我認爲你的查詢是作者真正想要的東西。 – MarcinJuraszek

+0

@MarcinJuraszek謝謝,這是一個很好的觀點。 –

+0

感謝大家的感激。謝謝@艾哈邁德 – Jaido