2

I am having trouble figuring out how to trigger "new Guid()" using AutoMapper.

This is my 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.

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();
}
Soumen Mukherjee
  • 2,953
  • 3
  • 22
  • 34
Ryukote
  • 767
  • 1
  • 10
  • 26

1 Answers1

3

Here you are creating instance of Guid() that creates an empty Guid i.e. 00000000-0000-0000-0000-000000000000 every time

You are looking for Guid.NewGuid() which creates new guid with unique value.

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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • I have used that before "new Guid" and it was the same result. – Ryukote Sep 25 '19 at 12:52
  • What issue you faced when you used `NewGuid()` – Prasad Telkikar Sep 25 '19 at 13:06
  • When I use NewGuid() I get default Guid value, only when SaveChanges triggers it generates value of Guid which is not default. I am thinking about removing that from model and trigger newGuid() only in Add method, cause Update will also trigger NewGuid() on mapping which is not correct thing. – Ryukote Sep 25 '19 at 13:48
  • Yes try it. While updating you can check `Guid? id` `HasValue` – Prasad Telkikar Sep 25 '19 at 18:43
  • @Ryukote Did you get chance to fix above issue. If you fixed what was the solution? – Prasad Telkikar Sep 26 '19 at 13:14
  • The problem was in AutoMapper. I have decided to have my own mappings and everything works now. And yes, I am using Guid.NewGuid() only when adding new user. – Ryukote Oct 03 '19 at 11:27
  • @Ryukote, I am glad that you reach out to me. If you have different explanation to fix this issue then you can answer it with all steps. If my answer is enough to solve your problem then accept it so others will take benefit of it – Prasad Telkikar Oct 03 '19 at 11:47