我正在尝试使用实体框架更新数据库,我使用automapper将我的实体映射到viewmodels,并以相同的方式将其映射回来:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([FromJson] MyCVViewModel model)
{
var userId = User.Identity.GetUserId();
//find the cv
CV cv = repository.FindCV(model.CVId);
//auto mapper mapping
Mapper.CreateMap<MyCVViewModel, CV>();
Mapper.CreateMap<MyCompanyViewModel, Company>();
cv = Mapper.Map<MyCVViewModel, CV>(model, cv);
//edit
repository.EditCV(cv);
}
当我将其映射回来时,公司实体内的外键CVid变为0,我认为在映射过程中丢失了一些东西,你如何映射外键?
这是我的视图模型和实体:
查看型号:
public class MyCVViewModel
{
public int CVId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Title cannot exceed 100 characters.")]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[StringLength(1000, ErrorMessage = "Statment cannot exceed 1000 characters.")]
[Display(Name = "Statement")]
public string Statement { get; set; }
public bool Reference { get; set; }
public List<MyCompanyViewModel> Companies { get; set; }
}
public class MyCompanyViewModel
{
[Required]
[StringLength(100, ErrorMessage = "Company Name cannot exceed 100 characters.")]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Job Title cannot exceed 100 characters.")]
[Display(Name = "Job Title")]
public string JobTitle { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "End Date")]
public DateTime EndDate { get; set; }
[Required]
[StringLength(1000, ErrorMessage = "Job Description cannot exceed 1000 characters.")]
[Display(Name = "Job Description")]
public string Description { get; set; }
}
实体:
public class CV
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CVId { get; set; }
public string Title { get; set; }
public string Statement { get; set; }
public bool Reference { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
public class Company
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string JobTitle { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Description { get; set; }
public virtual CV CV { get; set; }
public int CVId { get; set; }
}
这是我尝试更新时的错误消息:
操作失败:无法更改关系,因为一个或多个外键属性不可为空。对关系进行更改时,相关的外键属性将设置为空值。
我知道问题所在,但不知道如何告诉automapper保留外键值
答案 0 :(得分:2)
MyCompanyViewModel
类不包含CVId
属性的定义,因此默认情况下,Automapper不知道应该将值注入Company
的位置CVId
财产。public class MyCompanyViewModel
{
public int CVId { get; set; }
// Other properties
}
。只需定义它:
CompanyViewModel
然后为每个@for (int i = 0; i < Model.Companies.Count; i++)
{
// ...
@Html.HiddenFor(m => Model.Companies[i].CVId)
// ...
}
添加相应的隐藏输入字段到视图中:
{{1}}
你很高兴去!