1

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

5
  • Hello, at first, I strongly recommend you to use facades or at least repositories to extract code for manipulation with DB from controller actions. To your problem, I see that you are using some kind of mapper (maybe automapper?). What is your mapping profile definition for mapping entities to DTO ? Commented Sep 16, 2021 at 8:43
  • try creating a mapping config: Mapper.CreateMap<UserAccount, UserAccountDto>() .ForMember(dto => dto.Gender, opt => opt.MapFrom(x => x.Gender)); Commented Sep 16, 2021 at 8:47
  • @SamJ26 I actually use a repository which includes Gender, UserAccountType and Truck. I also have a mapper file with this CreateMap<UserAccount, UserAccountDto>(); Commented Sep 16, 2021 at 8:54
  • @ranton187 I have a mapping file with this CreateMap<UserAccount, UserAccountDto>();. Can you how to use (and where) .ForMember(dto => dto.Gender...)? Thanks Commented Sep 16, 2021 at 8:57
  • 1
    @ranton187 Ok... I try this ` CreateMap<UserAccount, UserAccountDto>().ForMember(dto => dto.Genders, opt => opt.MapFrom(x => x.Gender));` and indeed Gender is no more null. How to do with the other objects? Commented Sep 16, 2021 at 9:01

1 Answer 1

2

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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.