简体   繁体   English

AutoMapper 没有创建新的映射指南

[英]AutoMapper not creating new Guid on mapping

I am having trouble figuring out how to trigger "new Guid()" using AutoMapper.我无法弄清楚如何使用 AutoMapper 触发“new Guid()”。

This is my model:这是我的 model:

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

And this is my ViewModel:这是我的视图模型:

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

When I map from CountriesViewModel to Countries, Id in Countries have default value of Guid ( which is {00000000-0000-0000-0000-000000000000} ), instead of creating new Guid.当我从 CountryViewModel 到国家的 map 时,国家中的 Id 具有 Guid 的默认值(即 {00000000-0000-0000-0000-000000000000} ),而不是创建新的 Guid。

This is how I am doing that mapping:这就是我进行映射的方式:

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();
}

Here you are creating instance of Guid() that creates an empty Guid ie 00000000-0000-0000-0000-000000000000 every time在这里,您正在创建Guid()的实例,该实例创建一个空的 Guid,即00000000-0000-0000-0000-000000000000每次

You are looking for Guid.NewGuid() which creates new guid with unique value.您正在寻找Guid.NewGuid()来创建具有独特价值的新 guid。

Try below试试下面

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

For reference: Guid.NewGuid() vs. new Guid()供参考: Guid.NewGuid() 与 new Guid()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM