我为我糟糕的英语道歉。
我有一个使用实体框架的 ASP.NET Core Web API。对于我的一种方法,我想返回一个具有所有关系(一对一)的对象。
我的UserAccount
班级是:
[Table("UserAccount")]
public class UserAccount : BaseClass
{
// Foreign Keys
[ForeignKey(nameof(UserAccountType))]
public int UserAccountTypeId { get; set; }
[ForeignKey(nameof(Gender))]
public int GenderId { get; set; }
[ForeignKey(nameof(Truck))]
public int? TruckId { get; set; }
// Properties
public string LastName { get; set; }
public string FirstName { get; set; }
public string UserName { get; set; }
[DataType(DataType.EmailAddress)]
public string Mail { get; set; }
public string Login { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
// Navigation Properties
[IgnoreDataMember]
public virtual Gender Gender { get; set; }
[IgnoreDataMember]
public virtual UserAccountType UserAccountType { get; set; }
[IgnoreDataMember]
public virtual Truck Truck { get; set; }
}
我也使用 DTO 类:
public class UserAccountDto : BaseClassDto
{
// Foreign Keys
public int UserAccountTypeId { get; set; }
public int GenderId { get; set; }
public int TruckId { get; set; }
// Properties
public string LastName { get; set; }
public string FirstName { get; set; }
public string UserName { get; set; }
public string Mail { get; set; }
public string Login { get; set; }
public string Password { get; set; }
// Linked Objects
public virtual GenderDto Gender { get; set; }
public virtual UserAccountTypeDto UserAccountTypes { get; set; }
public virtual TruckDto Trucks { get; set; }
}
我想接收Gender
,UserAccountType
和 的所有关系对象Truck
。
我的方法是:
[HttpGet("GetByTruck/{truckId}", Name = "UserAccountByTruckId")]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<UserAccount>> GetByTruckId(int truckId)
{
if (truckId <= 0)
return BadRequest();
try
{
var userAccounts = await _repository.UserAccount.GetByTruckIdAsync(truckId);
var userAccountsResult = _mapper.Map<IEnumerable<UserAccountDto>>(userAccounts);
if (userAccountsResult == null)
return NotFound();
return Ok(userAccountsResult);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside GetById action int UserAccountController : {ex.Message} ");
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error");
}
}
在此方法中,该属性包含所有对象,但是当我尝试使用 Dto 类映射结果时,我丢失了关系对象。
所以我只有一个 UserAccount 对象,没有其他对象,如 Gender、UserAccountType 或 Truck。此对象变为 Null。有没有人可以帮助我?
谢谢
谢谢@ranton187 你救了我!希望可以帮助其他人,这是我问题的解决方案。我在映射配置文件中添加了这个:
CreateMap<UserAccount, UserAccountDto>() .ForMember(dto => dto.Genders, opt => opt.MapFrom(x => x.Gender)) .ForMember(dto => dto.UserAccountTypes, opt => opt.MapFrom( x => x.UserAccountType)) .ForMember(dto => dto.Trucks, opt => opt.MapFrom(x => x.Truck));
现在 Gender、UserAccountTypes 和 Truck 对象不再为 null。
感谢你们两位的快速帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句