Hello,
I am using asp.net core web api ani sql server in my project
Following is my code to get all users :
public async Task> GetAllUsers()
{
var users = await _usersContext
.UserMasters
.FromSqlRaw("exec uspGetAllUsers")
.ToListAsync();
return users;
}
it works fine,but I have to mention all columns of UsrMaster table in uspGetAllUsers procedure
I don't want to mention unnecessary columns in sql stored procedure
For ex, If Usermaster table has 10 columns , I have to mention all 10 columns in stored procedure, wheere as I just want to bind 4 columns in procedure
how to achieve this ?
Thank you
Cynthia SathuragiriPosted Dec 8, 2025, 4:52 AM
In Entity Framework Core, when you use .FromSqlRaw("exec uspGetAllUsers")
EF expects the result to match your entity (UserMaster) — meaning all mapped columns must be returned, even if you don’t use them.
That’s why your stored procedure must return all 10 columns.
UserMaster is an entity model. EF tracks it, so it expects
every mapped column
in the correct type
to build a complete entity
If the stored procedure returns less columns, EF can’t hydrate the entity ? it throws errors.
Let your stored procedure return only the fields you need (e.g., 4 columns), and map that to a DTO instead of the entity.
Create a DTO
public class UserDto
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
public DbSet UserDto { get; set; }
Stored Procedure returns only needed columns
SELECT UserId, UserName, Email, Mobile
FROM UserMaster
Query using DTO
public async Task
> GetAllUsers()
{
return await _usersContext
.UserDto
.FromSqlRaw("exec uspGetAllUsers")
.ToListAsync();
}
Sushant TorankarPosted May 24, 2022, 4:12 PM
Sachin SinghPosted May 24, 2022, 1:09 PM
> GetAllUsers()
Jay Krishna ReddyPosted May 24, 2022, 1:06 PM