简体   繁体   中英

Cannot retrieve data from SQL Server using Stored Procedure

I created a stored procedure that joins 2 tables and would only need a few fields from both the table.

ALTER PROC GetViewers 
@postId int
AS
BEGIN
    SELECT e.Email, e.ImagePath, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.SurName) AS 'FullName'
    FROM Posts as p
    JOIN Employees as e
    ON p.AuthorId = e.EmployeeId
    WHERE p.Id = @postId
END

I am using an entity framework core that is injected so to update, create, and everything I have to use this kind of syntax..

For Employee Table

var results = _context.Empkoyees.toListAsync();

var posts = _context.Posts.ToListAsync();

and this results and posts give me all the properties of Employees and Posts. But if I use a stored procedure using this

var postId = new SqlParameter("@postId", id);
var x = _context.Posts.FromSql("GetViewers @postId", postId).ToList();

I get an error that some of my required fields are not present. I don't want to use linq. Just the stored procedure please.

You have missed a parameter:

var post = new SqlParameter("@postId", postId);
var x = _context.Posts.FromSql("GetViewers @postId", post).ToList();

It looks like you need to add the parameter for the stored procedure in a different way.

have a look at the documentation below https://www.entityframeworktutorial.net/efcore/working-with-stored-procedure-in-ef-core.aspx

var x = _context.Posts.FromSql("GetViewers @postId", postId).ToList();

To something like this:

var param = new SqlParameter("@postId", postId);
var x = _context.Posts.FromSql("GetViewers @postId", param).ToList();

So the problem wasn't in the code but apparently Entity Framework Core has some limitations with stored procedures

  1. Result must be an entity type. This means that a stored procedure must return all the columns of the corresponding table of an entity.
  2. Result cannot contain related data. This means that a stored procedure cannot perform JOINs to formulate the result.
  3. Insert, Update and Delete procedures cannot be mapped with the entity, so the SaveChanges method cannot call stored procedures for CUD operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM