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

Sim*_*ons 6 .net c# 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;
        }
Run Code Online (Sandbox Code Playgroud)

但是得到这个错误

“LINQ to Entities 无法识别方法 'Model.Patient CreatePatient(Repository.PATIENT)' 方法,并且此方法无法转换为存储表达式。”

Rom*_*mbé 3

Patient您只需在 LINQ select 中创建新对象即可:

var patients = allpatients.Select(p => new Patient()  {
            FIRSTNAME = p.FIRSTNAME,
            MIDDLENAME = p.MIDDLENAME,
            SURNAME = p.SURNAME
        });
Run Code Online (Sandbox Code Playgroud)

或者定义一个Patient接受另一个Patient对象并使用提供的值初始化自身的构造函数Patient

public partial class Patient
{
    public Patient(Patient p)
    {
        this.FIRSTNAME = p.FIRSTNAME;
        this.MIDDLENAME = p.MIDDLENAME;
        this.SURNAME = p.SURNAME;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在 LINQ select 中使用它:

var patients = allpatients.Select(p => new Patient(p));
Run Code Online (Sandbox Code Playgroud)