Linq-to-sql Compiled Query returns object NOT belonging to submitted DataContext ?
Posted
by Vladimir Kojic
on Stack Overflow
See other posts from Stack Overflow
or by Vladimir Kojic
Published on 2010-03-18T19:31:02Z
Indexed on
2010/03/19
20:31 UTC
Read the original article
Hit count: 579
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 looks like compiled query is returning result from another data context
[TestMethod]
public void GetMachinesTest()
{
using (var unitOfWork = IoC.Get<IUnitOfWork>())
{
// Compile Query
var machine = Machines.GetMachineById(unitOfWork, 3);
}
using (var unitOfWork = IoC.Get<IUnitOfWork>())
{
var machineRepository = unitOfWork.GetRepository<Machine>();
// Get From Repository
var machineFromRepository = machineRepository.Find(m => m.MachineID == 2).SingleOrDefault();
var machine = Machines.GetMachineById(unitOfWork, 2);
VerifyHuskyHostMachine(machineFromRepository, 2, "Machine 2", "222222", "H400RS", "MachineIconB.xaml", false, true, LicenseType.Licensed, InterfaceType.HuskyHostV2, "10.0.97.2:8080", "10.0.97.2", 8080, "4.0");
VerifyHuskyHostMachine(machine, 2, "Machine 2", "222222", "H400RS", "MachineIconB.xaml", false, true, LicenseType.Licensed, InterfaceType.HuskyHostV2, "10.0.97.2:8080", "10.0.97.2", 8080, "4.0");
Assert.AreSame(machineFromRepository, machine); // FAIL
}
}
If I run other (complex) unit tests I'm getting as expected: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.
Another Important information is that this test is under TransactionScope!
UPDATE: It looks like next link is describing similar problem (is this bug solved ?): http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/9bcffc2d-794e-4c4a-9e3e-cdc89dad0e38
© Stack Overflow or respective owner