Good afternoon, please help me figure it out.
I have two models:
public class User { public int Id { get; set; } public string Email { get; set; } public string Password { get; set; } public Role Role { get; set; } public int RoleId { get; set; } } public class Role { public int Id { get; set; } public string Name { get; set; } } I draw attention to the fact that the User class is declared:
public Role Role { get; set; } If I extract data from the database as follows:
User user = db.Users.Include(u => u.Role).FirstOrDefault(u => u.UserID == model.UserId); Things are great, I get an instance of the User class, with all the members filled in, including User contains Role, from which I can take Name.
Looking at the SQL query that EF sends to the database, I saw the following:
PROCEDURE [dbo].[User_GetUserWithRole] @UserID int AS SELECT [Limit1].[Id] AS [Id], [Limit1].[Email] AS [Email], [Limit1].[Password] AS [Password], [Limit1].[RoleId] AS [RoleId], [Limit1].[Id1] AS [Id1], [Limit1].[Name] AS [Name] FROM ( SELECT TOP (1) [Extent1].[Id] AS [Id], [Extent1].[Email] AS [Email], [Extent1].[Password] AS [Password], [Extent1].[RoleId] AS [RoleId], [Extent2].[Id] AS [Id1], [Extent2].[Name] AS [Name] FROM [dbo].[Users] AS [Extent1] INNER JOIN [dbo].[Roles] AS [Extent2] ON [Extent1].[RoleId] = [Extent2].[Id] WHERE [Extent1].[UserID] = @UserID ) AS [Limit1] END I copied the code of this request and created a stored procedure from it.
Extracting data from the database using this stored procedure:
SqlParameter param = new SqlParameter("@UserID", UserId); var U = Database.SqlQuery<User>("User_GetUserWithRole @UserID", param); When I test this stored procedure in MsSQL Managment Studio, it returns all the data, including the Name field from the Role table. But when I look at the variable U, then Name is absent and Role = null. It turns out that the stored procedure cannot correctly form a User object as a result of a query, but why is that?