簡體   English   中英

AutoMapper 5.2.0 VIewModel到Core MVC中的Model問題

[英]AutoMapper 5.2.0 VIewModel to Model issue in Core MVC

楷模:

 public class Client{
    public int Id {get;set;}

    public string Name {get;set;}

    public Address Address {get;set;}

    public int AddressId  {get;set;}
}

public class Address{
   public int Id

   public string Address1 {get;set;}

   public string PostCode {get;set;}
}

查看型號:

public class ClientViewNodel{
        public int Id {get;set;}

        public string Name {get;set;}

        public Address Address {get;set;}

        public int AddressId  {get;set;}
    }

    public class AddressViewModel{
       public int Id

       public string Address1 {get;set;}

       public string PostCode {get;set;}
    }

制圖:

 Mapper.Initialize(config =>
    {
        config.CreateMap<ClientViewModel, Client>().ReverseMap();
        config.CreateMap<AddressViewModel, Address>().ReverseMap();
    });

控制器更新動作:

[HttpPost]
public async Task<IActionResult> Update(cLIENTViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return View("Client",viewModel);
    }

    var client= _clientRepository.GetClient(viewModel.Id);
    if (client == null) 
        return NotFound();

    client= Mapper.Map<ClientViewModel, Client>(viewModel);

    _clientRepository.Update(client);
    var result = await _clientRepository.SaveChangesAsync();

    if (result.Success)
    {
        return RedirectToAction("Index");
    }

    ModelState.AddModelError("", result.Message);

    return View("Client",viewModel);
}

問題是當_clientRepository.Update(client) ,我收到一條錯誤消息,說明:

無法跟蹤實體類型“客戶端”的實例,因為已經跟蹤了具有相同密鑰的此類型的另一個實例。 添加新實體時,對於大多數鍵類型,如果未設置任何鍵,則將創建唯一的臨時鍵值(即,如果為鍵屬性指定了其類型的默認值)。 如果要為新實體顯式設置鍵值,請確保它們不會與現有實體或為其他新實體生成的臨時值發生沖突。 附加現有實體時,請確保只有一個具有給定鍵值的實體實例附加到上下文。

當我調試代碼時,我可以看到,當我將viewModel映射到模型時,客戶端模型中的AddressID被設置為0.我猜這是導致問題的原因。

如何將viewModel映射回模型,其中將更新地址的詳細信息,例如Address1和Postcode而不是Id。

我還試圖在.ForMember(x => x.AddressId, opt => opt.Ignore())的映射中忽略Id for Address的映射

但它仍然將AddressId設置為0。

我錯過了什么?

當您執行Mapper.Map<ClientViewModel, Client>(viewModel) ,AutoMapper會創建一個新的Client對象,其ID與現有Client對象相同。

然后,您指示EntityFramework更新此對象圖。 實體框架不跟蹤您的新客戶端對象,因此它將對象附加到其內部魔術緩存/跟蹤醬。 由於ID的沖突,這會失敗。 因此,錯誤“無法跟蹤實體類型'客戶'的實例,因為已經跟蹤了具有相同密鑰的此類型的另一個實例”。

這也是0 AddressId的來源。 Address對象也是一個由AutoMapper創建的全新對象,該屬性的值為default(int) ,因為AutoMapper創建后它從未分配過其他值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM