2

I am trying to collect a value from a domain object through EF linq query. But I am getting an error pls can some help me correct this.

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: 
1
  • Try to replace this PatientIDs[k] = messageObject.ElementAt(k).Chatname; to this PatientIDs[k] = messageObject.ToList()[k].Chatname;
    – dvjanm
    Oct 21, 2013 at 6:28

1 Answer 1

2

The ElementAt method isn't supported. The messageObject query isn't executed till you call Count() and ElementAt() on it, and those are being treated as LINQ to Entity queries.

The action taken in the for loop can be rolled into your LINQ query by adding a Select statement:

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

    return query.ToArray();
}
2
  • 2
    Putting Select before Distinct can change results (on original code Distinct is done on whole objects, no on one property as in yours). Although I think your query is something author is really looking for. Oct 21, 2013 at 2:01
  • Thanks to you all Grateful. Thanks @Ahmad
    – Jaido
    Oct 21, 2013 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.