Paintbox
Paintbox

Reputation: 407

ASP.NET Core Web API with Entity Framework : return object with relationship

My apologies for my bad English.

I have an ASP.NET Core Web API using Entity Framework. For one of my methods, I want to return an object with all relationships (one to one).

My UserAccount class is:

[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; }
}

I also use a DTO class :

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; }
}

I want to receive all relationship object for Gender, UserAccountType and Truck.

My method is :

[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");
    }
}

In this method, the property contains all the objects but when I try to map result with the Dto class I lose relationship objects.

So I only have a UserAccount object without the other objects like Gender, UserAccountType or Truck. This objects become Null. Is there anybody who can help me?

Thanks

Upvotes: 1

Views: 1328

Answers (1)

Paintbox
Paintbox

Reputation: 407

Thanks @ranton187 you save me ! Hoping that can help others, here is the solution to my problem. I added this in the mapping config file :

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

Now Gender, UserAccountTypes and Truck objects are no more null.

Thanks to both of you for your fast help !

Upvotes: 2

Related Questions