4

编译查询:

   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 与 DB 映射的 POCO。

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

4

1 回答 1

1

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

DBDataContext.ObjectTrackingEnabled = false; // Read Only
于 2010-03-18T20:36:47.367 回答