簡體   English   中英

AutoMapper 沒有創建新的映射指南

[英]AutoMapper not creating new Guid on mapping

我無法弄清楚如何使用 AutoMapper 觸發“new Guid()”。

這是我的 model:

public class Countries
{
    public Guid Id { get; set; } = new Guid();
    public string Name { get; set; }
}

這是我的視圖模型:

public class CountriesViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

當我從 CountryViewModel 到國家的 map 時,國家中的 Id 具有 Guid 的默認值(即 {00000000-0000-0000-0000-000000000000} ),而不是創建新的 Guid。

這就是我進行映射的方式:

public async Task<CountriesViewModel> Add(CountriesViewModel country)
{
    var mapped = _mapper.Map<CountriesViewModel, Countries>(country);

    _context.Countries.Add(mapped);

    if (await _context.SaveChangesAsync() == 1)
    {
        _mapper = _countriesConfig.CreateMapper();
        return _mapper.Map<Countries, CountriesViewModel>(mapped);
    }

    return new CountriesViewModel();
}

在這里,您正在創建Guid()的實例,該實例創建一個空的 Guid,即00000000-0000-0000-0000-000000000000每次

您正在尋找Guid.NewGuid()來創建具有獨特價值的新 guid。

試試下面

public class Countries
{
    public Guid Id { get; set; } = Guid.NewGuid();
                                  //^^^^^^^^^^This was wrong in your code
    public string Name { get; set; }
}

供參考: Guid.NewGuid() 與 new Guid()

暫無
暫無

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

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