Reputation: 4560
I have a table line below.
Table 1: Users
UserId, Email,.....
Table 2: UserProfile
ProfileId, UserId,ProfileName,....
FK in Users.UserId --> UserProfile.UserId
When i get data like below..it's only retrieve User Object values only.I need to get the User Profile Objects values as well.
var returnObj = _context.Users.Where(x => x.UserId == userId).FirstOrDefault();
var returnData = _entityMapper.Map<Users, UsersDTO>(returnObj);
Upvotes: 0
Views: 272
Reputation: 36
Design the User and UserProfile classes as follows:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public UserProfile UserProfile { get; set; }
}
public class UserProfile
{
public int Id { get; set; }
public string ProfileName { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
They are One-to-one related entities, so
modelBuilder.Entity<User>()
.HasOne(_ => _.UserProfile)
.WithOne(_ => _.User);
Finally, load your data:
var result = _context.Users.Include( _ => _.UserProfile).Select( _ => new
{
Email = _.Email,
ProfileName = _.UserProfile.ProfileName,
}
).ToList();
this is based on EF Core
Upvotes: 2
Reputation: 74605
If you're using EF Core have a read of the documentation surrounding loading related data
If you're using EF 6 have a read of the documentation surrounding loading related data
LINQ-to-SQL is really old now (it was dead 10 years ago) and a deprecated product. If you are indeed using it, Google for "LINQ to sql loading related data"
Upvotes: 1