我正在使用EF Core和Automapper更新我的實體。我有一個名爲「Aluno」的實體,它與「Endereco」有關係。下面是代碼:使用automapper更新具有關係的實體
public class Aluno : ApplicationUser{
...
public Endereco Endereco { get; set; }
...
}
public class AlunoViewModel : UserViewModel
{
public int Id { get; set; }
public EnderecoViewModel Endereco { get; set; }
}
public class Endereco{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get;set; }
...
}
public class EnderecoViewModel {
public int Id { get;set; }
...
}
的automapper配置:
config.CreateMap<Aluno, AlunoViewModel>().ReverseMap();
config.CreateMap<Endereco, EnderecoViewModel>().ReverseMap();
AlunosController:
[HttpPut]
public JsonResult Put([FromBody]AlunoViewModel vm)
{
if (ModelState.IsValid)
{
var aluno = _context.Alunos
.Single(o => o.Id == vm.Id);
Mapper.Map(vm, aluno);
_context.SaveChanges();
Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
return Json(true);
}
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Json(false);
}
當我嘗試更新 「Aluno」 的實體,我就得到一個例外context.SaveChanges():
無法插入顯式當IDENTITY_INSERT設置爲OFF時,'Enderecos' 中的標識列的值。
但是我不想插入新的「Endereco」,只需更新實體「Aluno」,也許更新「Endereco」,這是正確加載var aluno內部。
我做錯了什麼?
我認爲你必須映射問題。保存操作前請檢查您的映射是否正確。您的Aluno映射需要「ForMember」函數來爲其屬性對象定義映射。你可以嘗試添加ForMember(i => i.Endereco,i => i.MapFrom(s => s.Endereco))。 – kizilsu
你是對的!你可以把它作爲答案發布,以便我可以標記它嗎?謝謝! – Munir
@Munir:請不要濫用AutoMapper綁定到實體,這會給您帶來很大麻煩,特別是在映射回集合時。 AutoMapper是和從未用於雙向映射。請閱讀AutoMapper作者的帖子,在這裏https://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/關於AutoMapper的用途和用途精細。試圖將其用於雙向綁定會導致a)您的域模型違反封裝以支持這種綁定,以及b)您的持久性模型/ ORM Mapper遇到綁定問題。 – Tseng