Linq 控制EF如何实现我的数据
有时,我希望对从数据库返回的数据进行基于代码的转换(例如)。将这样的转换放入IQueryable中会直接导致非常常见的结果: LINQ to Entities无法识别方法“method name”方法,并且无法将此方法转换为存储表达式 我知道我可以使用Linq 控制EF如何实现我的数据,linq,entity-framework,linq-to-entities,Linq,Entity Framework,Linq To Entities,有时,我希望对从数据库返回的数据进行基于代码的转换(例如)。将这样的转换放入IQueryable中会直接导致非常常见的结果: LINQ to Entities无法识别方法“method name”方法,并且无法将此方法转换为存储表达式 我知道我可以使用AsEnumerable或ToList在内存中完全执行查询和投影,但这将导致数据的两次传递 从数据库加载数据并将其具体化为实体类型 将数据(内存中)从实体类型转换为最终投影 无论如何,EF必须在内存中具体化数据,因此第二次传递看起来非常冗余。有没有
AsEnumerable
或ToList
在内存中完全执行查询和投影,但这将导致数据的两次传递
**作为旁注,EF团队实现此功能的自动版本是否可行?也就是说,任何无法翻译的表达式的任何部分都将在物化阶段执行?IMO混淆物化将导致一些不清楚的代码。考虑这一点:
// Name should always be Bob.
EF.ChangeMaterialization<PersonEntity>(p => new PersonEntity { Name = "Bob" });
// What is supposed to happen here? The database clearly says that there are
// multiple Joe's in my People table, but once I retrieve them they are no
// longer Joe's!
var query = People.Where(p => p.Name == "Joe");
2:
公共班级学生{
公共字符串名称{get;set;}
公共整数等级{get;set;}
}
公共班级学生公寓{
公共IEnumerable GetStudents(){
返回db.People.Select(p=>newstudent
{
名称=p.名称,
等级=p.测试平均值()
});
}
}
3:Google:EF计算列中的一些示例
public class Person {
public string Name { get; set; }
[Unmapped]
public string CalculatedName { get { return "Bob"; } }
}
public class Student {
public string Name { get; set; }
public int Grade { get; set; }
}
public class StudentRepository {
public IEnumerable<Student> GetStudents() {
return db.People.Select(p => new Student
{
Name = p.Name,
Grade = p.Tests.Average()
});
}
}