Compiled query:
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;
It seems that the compiled query returns the result from another data context.
[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 } }
If I run other (complex) unit tests, I get as expected: An attempt was made to connect or add an object that is not new, it may have been loaded from another DataContext.
Other important information is that this test is in TransactionScope (but the problem occurs even without transactions.)!
Im uses POCOs mapped to the database using XML.
UPDATE: Looks like the following link describes a similar problem (is this resolved?): Http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/9bcffc2d-794e-4c4a-9e3e-cdc89dad0e38
source share