[英]Mapping two models with AutoMapper
I have a Customer model which has a one-to-one relationship with an Address model.我有一个 Customer 模型,它与 Address 模型具有一对一的关系。 I'm using AutoMapper to map these values.
我正在使用 AutoMapper 来映射这些值。 I want to create a new Customer in the db using my API, which ideally will insert a new address row based on the information provided to the customer model.
我想使用我的 API 在数据库中创建一个新客户,理想情况下将根据提供给客户模型的信息插入一个新的地址行。
This is the SQL Exception I am receiving by Entity framework core: ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'AddressId', table 'dbo.Customers'; column does not allow nulls. INSERT fails.
这是我通过实体框架核心接收到的 SQL 异常:
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'AddressId', table 'dbo.Customers'; column does not allow nulls. INSERT fails.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'AddressId', table 'dbo.Customers'; column does not allow nulls. INSERT fails.
Note - BaseEntity is just including common properties like the ID, Concurrency check etc注意 - BaseEntity 仅包括常见属性,如 ID、并发检查等
Customers Model:客户型号:
public class Customer : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string UpdatedBy { get; set; }
public DateTime? LastContact { get; set; }
#region Navigation Properties
public int? AddressId { get; set; }
public string UserId { get; set; }
public User User { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
#endregion
}
My Address model:我的地址模型:
public class Address : BaseEntity
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
#region Navigation Properties
public virtual Customer Customer { get; set; }
#endregion
}
I am using a DTO class for the request, as follows:我为请求使用了 DTO 类,如下所示:
public class CustomerCreateDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string UserId { get; set; }
}
AddressDto:地址Dto:
public class AddressDto : BaseEntity
{
[Required]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string City { get; set; }
public string State { get; set; }
[Required]
[DataType(DataType.PostalCode)]
public string PostalCode { get; set; }
}
CustomerDto客户Dto
public class CustomerDto : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string UserId { get; set; }
public int AddressId { get; set; }
public string UpdatedBy { get; set; }
public DateTime? LastContact { get; set; }
public virtual UserDto User { get; set; }
public virtual AddressDto Address { get; set; }
public virtual ICollection<InvoiceDto> Invoices { get; set; }
}
Here is the AutoMapper configuration这是 AutoMapper 配置
public class MappingConfiguration : Profile
{
public MappingConfiguration()
{
CreateMap<AddressDto, Address>().ReverseMap();
CreateMap<CustomerDto, Customer>().ForMember(dst => dst.UserId,
opt => opt.MapFrom(src => src.User.Id)).ForMember(dst =>
dst.Address,
opt => opt.MapFrom(src => src.Address)).ReverseMap();
CreateMap<CustomerCreateDto, Customer>().ReverseMap();
}
}
And here is the Controller method.这是控制器方法。 I know that I can do it by manually setting the value with the
addressDto
object like customer.Address = address
but I want to see if there is a better way我知道我可以通过像
customer.Address = address
这样的addressDto
对象手动设置值来做到这一点,但我想看看是否有更好的方法
[HttpPost]
public async Task < IActionResult > Create([FromBody] CustomerCreateDto customerDto)
{
if (customerDto == null || !ModelState.IsValid) {
return BadRequest(ModelState);
}
var addressDto = new AddressDto {
AddressLine1 = customerDto.AddressLine1,
AddressLine2 = customerDto.AddressLine2,
City = customerDto.City,
State = customerDto.State,
PostalCode = customerDto.PostalCode,
CreatedDate = DateTime.Now,
};
var user = await _userManager.FindByIdAsync(customerDto.UserId);
var address = _mapper.Map<Address>(addressDto);
var customer = _mapper.Map<Customer>(customerDto);
customer.CreatedDate = DateTime.Now;
var result = await _customerRepository.CreateAsync(customer);
if (result) return Created("Created", new { customer });
// if we got this far it means the request failed
return new
StatusCodeResult(StatusCodes.Status500InternalServerError);
}
The functionality I was looking for was achieved by changing the CustomerCreateDto to:我正在寻找的功能是通过将 CustomerCreateDto 更改为:
public class CustomerCreateDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string UserId { get; set; }
public virtual AddressDto Address { get; set; }
}
Mapping Configurations:映射配置:
public class MappingConfiguration : Profile
{
public MappingConfiguration()
{
CreateMap<AddressDto, Address>().ReverseMap();
CreateMap<CustomerDto, Customer>().ForMember(dst => dst.UserId,
opt => opt.MapFrom(src => src.User.Id));
CreateMap<CustomerCreateDto, Customer>().ForMember(dst => dst.Address,
opt => opt.MapFrom(src => src.Address)).ReverseMap().ReverseMap();
}
}
My controller:我的控制器:
[HttpPost]
public async Task<IActionResult> Create([FromBody] CustomerCreateDto customerDto)
{
if (customerDto == null || !ModelState.IsValid) {
return BadRequest(ModelState);
}
var customer = _mapper.Map<Customer>(customerDto);
customer.CreatedDate = DateTime.Now;
var result = await _customerRepository.CreateAsync(customer);
if (result) return Created("Created", new { customer });
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.