0

可能重复:
不允许在查询中显式构造实体类型 [MyClass]

我正在使用 linq to sql - 我正在尝试获取以下 2 个道具的计数(打开和关闭任务)但是我收到一个异常,说我无法在查询中加载实体,我该如何实现?

我的代码:

var milestones = ReadOnlySession.All<Milestone>()
    .Where(x => x.InstructionID == instructionid)
    .OrderBy(x => x.Name)
    .Select(x => new Milestone
    {
        Name = x.Name,
        InstructionID = x.InstructionID,
        Body = x.Body,
        Deadline = x.Deadline,
        MilestoneID = x.MilestoneID,
        TotalClosedTasks = 
            ReadOnlySession.All<InstructionTask>()
            .Count(c => c.Milestone == x.MilestoneID && !c.IsOpen),
        TotalOpenTasks = 
            ReadOnlySession.All<InstructionTask>()
            .Count(c => c.Milestone == x.MilestoneID && c.IsOpen)
    })
    .ToList();

错误:

消息:不允许在查询中显式构造实体类型“Surventrix.Domain.Model.Entities.Milestone”。

来源:System.Data.Linq

注意: ReadOnlySession - 对数据上下文的抽象,为我提供了 All、Single(基本上获取 T 的所有实体)

4

2 回答 2

0

尝试在 order 子句后添加 AsEnumerable,如果您没有性能问题,这应该可以解决问题。

var milestones = ReadOnlySession.All<Milestone>()
.Where(x => x.InstructionID == instructionid)
.OrderBy(x => x.Name).AsEnumerable()
.Select(x => new Milestone
{
于 2012-08-16T10:12:29.310 回答
0

我认为您必须将 Milestone 对象的创建(您还设置额外的总关闭/打开任务属性)与查询分开。在下面的查询中,来自数据库的匿名对象,然后*新的 Milestone 对象被创建。这样,它仍然是单个查询,假设 ReadOnlySession 仍然返回 IQueryable。

var milestones = ReadOnlySession.All<Milestone>()
    .Where(x => x.InstructionID == instructionid)
    .OrderBy(x => x.Name)
    .Select(x => new { 
        Milestone = x,
        TotalClosedTasks = ReadOnlySession.All<InstructionTask>()
                                .Count(c => c.Milestone == x.MilestoneID && !c.IsOpen)
        TotalOpenTasks = ReadOnlySession.All<InstructionTask>()
                                .Count(c => c.Milestone == x.MilestoneID && c.IsOpen)
    })
    .AsEnumerable()
    .Select(x => new Milestone {
        Name = x.Milestone.Name,
        InstructionID = x.Milestone.InstructionID,
        Body = x.Milestone.Body,
        Deadline = x.Milestone.Deadline,
        MilestoneID = x.Milestone.MilestoneID,
        TotalClosedTasks = x.TotalClosedTasks,
        TotalOpenTasks = x.TotalOpenTask
    })
    .ToList();
于 2012-08-16T10:14:44.720 回答