[英]Using stored procedure to get data from multiple columns and display it in a View
I want to display data from two tables in a view with the help of a stored procedure. 我想借助存储过程在视图中显示两个表中的数据。 I'm getting stuck in retrieving records, can't write view model class in DbSet
as its wrong, have posted my code. 我被困在检索记录中,无法在DbSet
编写视图模型类,因为它是错误的,已经发布了我的代码。
And also I want to pass data from the controller to view in strongly typed. 我也想从控制器传递数据以查看强类型。
Please refer snap short for further understanding. 请参考简短说明以进一步了解。
The count of data is correct but there is no data in it. 数据计数正确,但其中没有数据。
Model 模型
public class tblStudents
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime? CreatedDate { get; set; }
}
public class tblStudentDetails
{
[Key]
public int StudentId { get; set; }
public string Address { get; set; }
public DateTime? CreatedDate { get; set; }
}
//This class contains columns from both the tables
public class AllDataa
{
public class Dataa
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
}
Viewmodel: 视图模型:
public class VMStudentDetails
{
public List<tblStudents> students { get; set; }
public tblStudentDetails StudentDetails { get; set; }
public IEnumerable<AllDataa> AllData { get; set; }
}
Stored procedure: 存储过程:
CREATE PROCEDURE usp_StudentDetail
AS
BEGIN
SELECT
S.Name, SD.Address
FROM
tblStudents S
INNER JOIN
tblStudentDetails SD ON S.Id = Sd.StudentId
END
Controller 控制者
public ActionResult Index()
{
var model = new MVCLearning.Models.VMStudentDetails();
//What to write in Sqlquery?
//model.AllData = db.Database.SqlQuery<>("usp_StudentDetail").ToList();
//This is not working the data is not coming in Alldata
model.AllData = db.Database.SqlQuery<AllDataa>("usp_StudentDetail").ToList();
return View(model);
}
If you are using code first approach, then the recommended way would be to join both the tables through code like below 如果您使用的是代码优先方法,那么建议的方法是通过如下代码将两个表连接起来
from student in tblStudents
Join details in tblStudentDetails
On student.id equals details.studentid
Select new AllData() {Id =student.id, name = student. Name, Address =details.Address}
This is more similar to SP you have written 这更类似于您编写的SP
Thanks for your support I have fixed it the issue was in the AllDataa class there was another class in it which is why it was not working. 感谢您的支持,我已解决了该问题,该问题在AllDataa类中存在,因此其中还有另一个类,这就是为什么它不起作用的原因。
public class AllDataa
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.