I need help on how to get a data from a one to many. I'm using .NET Core 3.1 Web API with Entity Framework.
Table 1 : User
ID Guid
UserName String
Table 2 : UsererAgency
UserId GUID
AgencyCode String
Table 3 Agency
AgencyCode string
AgencyName String
The path is from table User
, column ID
to UserAgency.UserID
and from UserAgency
to Agency
using the AgencyCode
column.
I want to get all the users and their Agencies. So I want to return just:
- ID from User
- AgencyCode and AgencyName from Agency table.
Here are my POCO's that I'm using to get data back form entity framework.
User
public User()
{
public User()
{
UserAgency = new HashSet<UserAgency>();
}
[NotMapped]
public GUID ID { get; set; }
[NotMapped]
public virtual ICollection<UserAgency> UserAgency { get; set; }
}
public class UserAgency
{
[Key]
public Guid UserId { get; set; }
[Key]
[ForeignKey("Agency")]
public string AgencyCode { get; set; }
[NotMapped]
public virtual Agency Agency { get; set; }
[NotMapped]
public virtual User User { get; set; }
}
public partial class Agency
{
public Agency()
{
Employee = new HashSet<Employee>();
UserAgency = new HashSet<UserAgency>();
User = new HashSet<ApplicationUser>();
}
public string AgencyCode { get; set; }
publicstring AgencyName { get; set; }
[NotMapped]
public virtual ICollection<UserAgency> UserAgency { get; set; }
[NotMapped]
public virtual ICollection<User> User { get; set; }
}
var members = await _unitOfWork.UserRepository.FindAllAsync(null, null, new List<string> {"UserAgency" });
It is returning my data correctly. Returning all my Users (which is correct) and all the UserAgency with all their Agency under Useragency. I guess I don't know how to drill down or how to format my DTO. Would I use AutoMapper or could I select what I need?