Jaido
Jaido

Reputation: 188

Error in Linq query in Entity Framework

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: 

Upvotes: 2

Views: 1671

Answers (1)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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

Upvotes: 2

Related Questions