I am new to ASP.NET MVC and Entity Framework code first approach. I want to implement a complex [with INNER JOIN, FUNCTION etc.] stored procedure using this approach. I have gone through many question on SO but I get more confused after reading these questions.
What I have done
I first successfully created database using code first approach. As per my research on google, I created a stored procedure with an INNER JOIN
in my database.
Then I created class matching with resultant columns from the stored procedure. Then I added this class to my ApplicationDbContext
class like this
public DbSet<AllInfo> allInfos { get; set; }
Then in my APIController I call stored procedure like this
var registerUser = db.allInfos.FromSql($"SP_GetInfo").ToList();
but I get error saying AllInfo
has no key
defined. Also AllInfo
table is added to database because I have added reference in ApplicationDbContext
.
My questions
Why does
AllInfo
class needs a key when I want this class just to show information retrieved from the stored procedure?If I have to create class for each stored procedure, then there will be so many classes in my project. Is my understanding correct ?
This link says DO NOT create SP when using stored procedures. Then what is the method to call complex queries ?
Kindly help with my confusion.
Thanks!
EDIT
Here is my query. it is not as much complex though but further queries might be complex
SELECT
a.UserId,
a.FullUserName,
a.BirthDate,
a.BloodGroup,
a.ContactNo,
a.Email,
a.Gender,
ISNULL(dbo.Fn_FetchEducationInfo(a.UserId), '-NA-') AS Education
FROM
RegisterUsers AS a
Function :
ALTER FUNCTION [dbo].[Fn_FetchEducationInfo]
(@Id VARCHAR(100))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Education AS NVARCHAR(MAX)
SELECT
@Education = STUFF((SELECT ' ' + Education +','
FROM Tbl_Education as edu
INNER JOIN OPersonMEducations opme ON edu.EduId = opme.EduId
INNER JOIN RegisterUsers RU ON RU.UserId = opme.Id
WHERE RU.UserId = @Id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM
RegisterUsers AS a
--print @Education
--'UPB005'
RETURN @Education
END