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();
}
Here you are creating instance of Guid()
that creates an empty Guid ie 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.