c# - Entity Framework 中的 Linq 查询错误

标签 c# .net entity-framework

我正在尝试通过 EF 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: 

最佳答案

不支持 ElementAt 方法。 messageObject 查询只有在调用 Count()ElementAt() 时才会执行,并且这些查询将被视为 LINQ to Entity查询。

通过添加 Select 语句,可以将 for 循环中执行的操作整合到 LINQ 查询中:

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

    return query.ToArray();
}

关于c# - Entity Framework 中的 Linq 查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484594/

相关文章:

c# - 将对象添加到 Entity Framework 上下文大约需要 1.5 秒

c# - 自定义Membership provider时如何管理ProviderUserKey

c# - Builder 与 Facade 设计模式

c# - NHibernate Linq : how to use StartsWith on an integer type

entity-framework - Entity Framework 代码第一个问题无法确定类型之间关联的主体

c# - 为什么 NLog 在记录大量消息时会漏掉一些消息?

c# - 使用触发器更改已绑定(bind)到 View 模型的属性

ASP.Net 验证器样式

c# - 使用 LINQ 返回子对象

c# - 跨不同 Linq-to-SQL 上下文的实体相等性