Linq-to-sql Compiled Query返回的对象不属于提交的DataContext?

编译查询:

   public static class Machines
   {
      public static readonly Func<OperationalDataContext, short, Machine>
          QueryMachineById = 
           CompiledQuery.Compile((OperationalDataContext db, short machineID) =>
           db.Machines.Where(m => m.MachineID == machineID).SingleOrDefault()
     );

     public static Machine GetMachineById(IUnitOfWork unitOfWork, short id)
     {
        Machine machine;

        // Old code (working)
        //var machineRepository = unitOfWork.GetRepository<Machine>();
        //machine = machineRepository.Find(m => m.MachineID == id).SingleOrDefault();

        // New code (making problems)
        machine = QueryMachineById(unitOfWork.DataContext, id);

        return machine;
     }

看起来编译的查询返回来自另一个数据上下文的结果

  [TestMethod]
  public void GetMachinesTest()
  {
     using (var unitOfWork = IoC.Get<IUnitOfWork>())
     {
        // Compile Query
        var machine = Machines.GetMachineById(unitOfWork, 3);
        // In this unit of work everything works… 
        // Machine from repository (table) is equal to Machine from compile query.
     }

     using (var unitOfWork = IoC.Get<IUnitOfWork>())
     {
        var machineRepository = unitOfWork.GetRepository<Machine>();

        // Get From Repository
        var machineFromRepository = machineRepository.Find(m => m.MachineID == 2).SingleOrDefault();
        // Get From COmpiled Query
        var machine = Machines.GetMachineById(unitOfWork, 2);

        VerifyMachine(machineFromRepository, 2, "Machine 2", "222222", ...);
        VerifyMachine(machine, 2, "Machine 2", "222222", ...);

        Assert.AreSame(machineFromRepository, machine);       // FAIL
     }
  }

如果我运行其他(复杂)单元测试,我会得到预期的:
 已尝试附加或添加非新的实体,可能已从另一个DataContext加载.

另一个重要信息是此测试是在TransactionScope下进行的(但即使没有事务处理,问题也会出现.)!

我正在使用使用XML映射到数据库的POCO.

更新:
看起来下一个链接描述了类似的问题(这个bug是解决了吗?):
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/9bcffc2d-794e-4c4a-9e3e-cdc89dad0e38

最佳答案 您可以尝试将上下文的ObjectTrackingEnabled设置为false.这在同样的情况下帮助了我,但我后来在更新和插入记录时打开它.

DBDataContext.ObjectTrackingEnabled = false; // Read Only
点赞