c# - LINQ to Entities 无法识别该方法,并且该方法无法转换为 store 表达式

标签 c# .net entity-framework asp.net-web-api

我有以下代码使用 EF 获取所有数据,然后尝试将它们转换为模型,如下所示。

var patients = allpatients.Select(p => CreatePatient(p));

    public Patient CreatePatient(PATIENT p)
        {
            Patient patient = new Patient();

            patient.FIRSTNAME = p.FIRSTNAME;
            patient.MIDDLENAME = p.MIDDLENAME;
            patient.SURNAME = p.SURNAME;

            return patient;
        }

但是得到这个错误

"LINQ to Entities does not recognize the method 'Model.Patient CreatePatient(Repository.PATIENT)' method, and this method cannot be translated into a store expression."

最佳答案

此语句不能直接转换为任何等效的 SQL 命令:

var patients = allpatients.Select(p => CreatePatient(p));

在 LINQ to Entities(EF 数据上下文)中使用自定义扩展方法的常用方法是先对模型执行查询(可以转换为 SQL 语句),然后使用自定义扩展方法 外面查询上下文(这只是一个例子):
var patients = allpatients.Select(p => new Patient() 
{
     FIRSTNAME = p.FIRSTNAME,
     MIDDLENAME = p.MIDDLENAME,
     SURNAME = p.SURNAME
});

foreach (Patient pt in patients)
{
    // iterate through Patient collection
    // use your custom method here
}

请注意,如果自定义方法成为 new 的一部分,也会发生相同的错误。 LINQ 查询中的模型分配,如下例所示:
var patients = allpatients.Select(p => new Patient() 
{
     PATIENTID = ToInt32(p.PATIENTID), // ToInt32 is a custom extension method, e.g. converting string to int
     FIRSTNAME = p.FIRSTNAME,
     MIDDLENAME = p.MIDDLENAME,
     SURNAME = p.SURNAME
});

这是上述使用的正确方法:
var patients = allpatients.Select(p => new Patient() 
{
     PATIENTID = p.PATIENTID, // leave the selected property as-is
     FIRSTNAME = p.FIRSTNAME,
     MIDDLENAME = p.MIDDLENAME,
     SURNAME = p.SURNAME
});

// another method content
foreach (Patient pt in patients)
{
    other.PATIENTID = ToInt32(pt.PATIENTID);
}

引用:

LINQ to Entities does not recognize the method

关于c# - LINQ to Entities 无法识别该方法,并且该方法无法转换为 store 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45319797/

相关文章:

c# - 如何将昨天的日期分配给参数 C#

C# 这个方法线程安全吗?

c# - WebClient 下载文件损坏

.net - 我应该在 .NET 中为 COM 互操作使用哪个集合接口(interface)?

.NET Core MSTest 参数

c# - EF - WithOptional - 左外连接?

c# - 使用注册表值启动应用程序?它出什么问题了? .net 2.0 ONLY 请

c# - 寻找字符串操作的最佳方式

c# - orm 和 ADO.net 有什么区别?

C# GUI 可编辑 DataGridView