如何将模型转换为实体?

时间:2018-10-18 05:40:04

标签: asp.net-mvc entity-framework

我无法将数据保存在数据库中,因为模型无法转换为实体, 我从模型中获取数据,但是添加功能无法添加到数据库中。

[HttpPost]
public ActionResult Create(Patient Patient)
{
    _context.Patients.Add(Patient); "(Error here)"
    try
    {
        _context.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        foreach (var entityValidationErrors in ex.EntityValidationErrors)
        {
            foreach (var validationError in entityValidationErrors.ValidationErrors)
            {
                Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
            }
        }
    }

    return RedirectToAction("Index", "Patients");
}

}

  

错误:无法从“ CandidateScreening.Models.Patient”转换为“ CandidateScreening.Data.Entities.Patient”

2 个答案:

答案 0 :(得分:1)

对于视图模型和数据模型,您有2个不同的类,当然它们两者不能隐式地相互转换。启用转换的最简单方法是使用implicit operator(或explicit operator,具体取决于上下文)在视图模型和数据模型之间进行转换,请参见以下示例:

public static implicit operator Patient(PatientVM patient)
{
    return new Patient
    {
        // list of properties
        // example:
        // PatientId = patient.PatientId
    };
}

然后按如下所示在POST操作方法中将视图模型内容分配给数据模型:

[HttpPost]
public ActionResult Create(PatientVM patient)
{
    Patient patientData = patient;

    _context.Patients.Add(patientData);

    // other stuff

    return RedirectToAction("Index", "Patients");
}

注意:在示例中,有意更改了视图模型类名称,以区分数据模型和视图模型类。

答案 1 :(得分:1)

您也可以使用Automapper。这是一个示例:

CandidateScreening.Data.Entities.Patient patient = Mapper.Map<CandidateScreening.Data.Entities.Patient>(patientVm);//where patientVm has type CandidateScreening.Models.Patient