I'm hoping someone has had this issue before and can help me out. I have an ASP.NET Core 7 web assembly controller that returns a User object back to the client. The User object has a list of Roles associated with it.
When I issue an HTTP GET from the client to the server, everything seems to be working okay. However, when the object is returned back to the client, the embedded list of Roles isn't included.
Here is my client code:
public async Task<Lightwave.Data.User> GetUserByUserId(string expand = default(string), int userId = default(int))
{
var uri = new Uri(_baseUri, $"Users({userId})");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
var response = await _httpClient.SendAsync(httpRequestMessage);
var json = await response.Content.ReadAsStringAsync(); // No Roles List
return JsonConvert.DeserializeObject<Data.User>(json);
}
Client JSON response (no roles list):
{
"UserId": 2,
"UserName": "Administrator",
"FirstName": "Test",
"LastName": "User",
"EmailAddress": "[email protected]",
"Active": true,
"LastLogin": "2023-04-17T10:26:01.253Z",
"LastModifiedUser": null,
"LastModifiedDate": "2023-04-14T10:53:33.067Z"
}
Controller code:
[HttpGet("/odata/Lightwave/Users(UserId={UserId})")]
public User GetUser(int key)
{
var user = _context.Users
.Include(i => i.Roles)
.Where(i => i.UserId == key)
.SingleOrDefault();
// for debug purposes
var json = JsonConvert.SerializeObject(user);
// end debug
return user;
}
Controller JSON (note: roles are included):
{
"UserId": 2,
"UserName": "Administrator",
"FirstName": "Test",
"LastName": "User",
"EmailAddress": "[email protected]",
"Active": true,
"LastLogin": "2023-04-17T10:26:01.253",
"LastModifiedUser": null,
"LastModifiedDate": "2023-04-14T10:53:33.067",
"Roles": [
{
"RoleId": 1,
"RoleName": "Administrator",
"Users": []
}
]
}
User/Role objects:
public partial class User
{
public User()
{
Roles = new List<Role>();
UserQueries = new List<UserQuery>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? EmailAddress { get; set; }
public bool Active { get; set; } = true;
public DateTime? LastLogin { get; set; }
public string? LastModifiedUser { get; set; }
public DateTime? LastModifiedDate { get; set; }
public ICollection<Role> Roles { get; set; }
}
[Table("Role", Schema = "dbo")]
public partial class Role
{
public Role()
{
Users = new List<User>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
[Required]
public string RoleName { get; set; }
//public ICollection<UserRole> UserRoles { get; set; }
public ICollection<User> Users { get; set; }
}
json = JsonConvert.SerializeObject(user);? I cannot see any mappings with user and roles. How they are related could you please share?