【问题标题】:AutoMapper not creating new Guid on mappingAutoMapper 没有创建新的映射指南
【发布时间】:2019-09-25 12:43:57
【问题描述】:

我无法弄清楚如何使用 AutoMapper 触发“new Guid()”。

这是我的模型:

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

这是我的 ViewModel:

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

当我从国家视图模型映射到国家时,国家中的 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();
}

【问题讨论】:

    标签: c# automapper guid


    【解决方案1】:

    在这里,您正在创建 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() vs. new Guid()

    【讨论】:

    • 我在“new Guid”之前使用过它,结果是一样的。
    • 您在使用NewGuid()时遇到了什么问题
    • 当我使用 NewGuid() 时,我得到默认的 Guid 值,只有当 SaveChanges 触发时,它才会生成非默认的 Guid 值。我正在考虑从模型中删除它并仅在 Add 方法中触发 newGuid(),因为 Update 也会在映射上触发 NewGuid(),这是不正确的。
    • 是的,试试吧。更新时可以查看Guid? idHasValue
    • @Ryukote 你有机会解决上述问题吗?如果你修好了,解决办法是什么?
    猜你喜欢
    • 2017-05-19
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2017-01-15
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多