I have a model like below
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string? Phone { get; set; } = string.Empty;
[Key]
public string Email { get; set; }
public virtual UserRole Role { get; set; }
[ForeignKey("Role")]
public int RoleID { get; set; }
}
public class UserRole
{
public int RoleID { get; set; }
public string RoleName { get; set; } = String.Empty;
public ICollection<User> Users { get; set; }
}
I need to get list of all users with RoleName. I tried the below, but its not working. Can someone please help me
var user = context.UserModel
.Include(x => x.Role.Select(x => x.RoleName)
.AsNoTracking()
Expected output format
[
{
"userID": 0,
"firstName": "string",
"lastName": "string",
"phone": "string",
"email": "string",
"roleName": "string",
"roleID": 0
}
]
CodePudding user response:
Try this way
var user = context.UserModel
.Select(x => new UserModel
{
UserId = x.UserID,
FirstName = x.FirstName,
LastName = x.LastName,
Phone = x.Phone,
Email = x.Email,
RoleName = x.Role.RoleName,
RoleID = x.Role.RoleID,
})
.ToList();