Compiled Linq-to-sql query returns an object not belonging to the presented DataContext?

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; // 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; } 

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

+4
source share
2 answers

This is a mistake and it will not be fixed.

A similar problem was described in a post from the link below. I tried not to use PK in the compiled request as suggested, but got the same problem. Thus, there is a problem with compiled requests bypassing the cache.

Workaround for caching LINQ to SQL IDs and compiled Query?

+1
source

You can try setting the ObjectTrackingEnabled context object to false. This helped me in the same situation, but later I turned it on, updating and inserting records.

 DBDataContext.ObjectTrackingEnabled = false; // Read Only 
+1
source

Source: https://habr.com/ru/post/1304493/


All Articles