我希望借助存储过程在视图中显示两个表的数据。我在查找记录时遇到困难,无法在DbSet
中编写视图模型类作为错误,已发布我的代码。
我还希望将数据从控制器传递到强类型的视图。
请参阅快照以获得进一步了解。
数据计数正确但其中没有数据。
模型
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; }
}
}
视图模型:
public class VMStudentDetails
{
public List<tblStudents> students { get; set; }
public tblStudentDetails StudentDetails { get; set; }
public IEnumerable<AllDataa> AllData { get; set; }
}
存储过程:
CREATE PROCEDURE usp_StudentDetail
AS
BEGIN
SELECT
S.Name, SD.Address
FROM
tblStudents S
INNER JOIN
tblStudentDetails SD ON S.Id = Sd.StudentId
END
控制器
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);
}
答案 0 :(得分:0)
如果您使用代码优先方法,那么推荐的方法是通过以下代码加入两个表
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}
这与你写的SP更相似
答案 1 :(得分:0)
感谢您的支持我已经解决了问题,因为在AllDataa类中有另一个类,这就是它无法正常工作的原因。
public class AllDataa
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}