我将向您展示如何在EF core中使用视图。 我们有老师和系课程。
教师班
public class Teacher
{
public int TeacherId { get; set; }
public string FullName { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
部门课程
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public List<Teacher> Teachers=>new List<Teacher>();
}
现在我们必须在Sql服务器中创建一个视图
SelectNameAndDpartment视图
Create VIEW SelectNameAndDpartment AS SELECT FullName, DepartmentName FROM Departments as d INNER JOIN Teachers as t ON d.DepartmentId = t.DepartmentId GO
然后我们要创建另一个类并在相关类中获取属性
public class TeacherService
{
public string FullName { get; set; }
public string DepartmentName { get; set; }
}
现在,我们在 Dbcontext 类
中使用 dbQuery 属性但是,属性名称必须与SQL Server中的视图名称相同,并且列名称与类属性相同
public DbQuery<TeacherService> SelectNameAndDepartment { get; set; }
现在您可以使用它并检索数据。