ASP.带有实体框架的.NET Core Web API:返回带有关系的对象



很抱歉我的英语很差。

我有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,UserAccountTypeTruck的所有关系对象。

我的方法是:
[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对象,没有其他对象,如性别,UserAccountType或卡车。该对象变为Null。有人能帮我吗?

感谢

谢谢@ranton187你救了我!希望能帮助别人,这里是我解决问题的方法。我在映射配置文件中添加了这个:

CreateMap

相关内容

最新更新