我正在使用 C# 和实体框架 asp.net MVC 4
基本上我希望我的索引页只有我的 SQL 表中的几列。但我仍然想使用那个 sql 表类。这是我的示例,用于使用 POCO 类的 Enity 框架从 SQL 中仅选择某些列。
//in the controller I get back a list of student entities
var students = from s in studentRepository.GetStudents()
select s;
//Below in the repository I have a function getstudents that with return all students
public IEnumerable<Student> GetStudents()
{
//I create a list of anonymous types
var result = (from a in context.Students
select new
{
FirstMidName = a.FirstMidName,
}
).ToList();
//I set the anonymous types to student types
IEnumerable<Student> x = from k in result
select new Student
{
FirstMidName = k.FirstMidName
};
//I return the list of students with only there name variable set
return x;
}
这是所有创建的sql
SELECT
1 AS [C1],
[Extent1].[FirstName] AS [FirstName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[Discriminator] = N'Student'
所以基本上我想知道我的方法有什么问题吗?执行此操作可能出现的任何问题。还有更好的方法吗?