Entity framework EF能否选择多个已转换的集合?
假设我有一个名为Request的实体,它包含如下子实体的集合:Entity framework EF能否选择多个已转换的集合?,entity-framework,entity-framework-4,entity-framework-4.1,ef-code-first,Entity Framework,Entity Framework 4,Entity Framework 4.1,Ef Code First,假设我有一个名为Request的实体,它包含如下子实体的集合: public class Request { public int RequestID { get; set; } //Navigation Properties public ICollection<Task> Tasks { get; set; } public ICollection<Question> Questions { get; set; } } 公共类请求
public class Request
{
public int RequestID { get; set; }
//Navigation Properties
public ICollection<Task> Tasks { get; set; }
public ICollection<Question> Questions { get; set; }
}
公共类请求
{
public int RequestID{get;set;}
//导航属性
公共ICollection任务{get;set;}
公共ICollection问题{get;set;}
}
我想检索一个包含Tasks和Questions集合的对象,我可以使用include()
进行检索,但我不需要这些集合中的所有字段
假设我只对从每个任务
和问题
实体检索名称和日期字段感兴趣
我知道如何执行此操作的唯一方法是在多个查询中调用select()
,以检索每个转换的集合
有没有一种方法可以在到DB的单程中实现这一点?我相信这并不完全是您想要的,但这应该只是到数据库的一次往返,并且应该让您从正确的方向开始:
entitycontext.Requests.Select(t => new {
TaskName = t.Questions.First().Name,
QuestionName = t.Tasks.First().Name
});
您应该能够执行以下操作:
var requests = context.Request
.Select(r => new
{
id = R.RequestID,
tasks = R.Tasks
.Select(t => new
{
Name = t.Name,
Date = t.Date
});
questions = R.Questions
.Select(q => new
{
Name = q.Name,
Date = q.Date
});
});
我很确定
Include
不是必需的,因为查询本身已经加入,以便返回加入的项目。谢谢Erik。我把事情复杂化了:)