none
Different Datacontexts error. RRS feed

  • Question

  •  

    Hi,

    Im trying to accomplish a SQL query like this in linq:

    SELECT me.me_id,me_name, case when (select count(*) from menuitems mi where mi.me_id=me.me_id)>0 then 1 else 0 end

     

    FROM Menus me

    WHERE mt_id = 2

    ORDER BY me_name

     

     

    My first approach with linq was this:

     

    IEnumerable<Node> nodes = (from me in DataContext.Menus

    where me.mt_id == menuType

    select new Node

    {

    Id = me.me_id.ToString(),

    Text = me.me_name,

    HasChilds =

    ( (from mi in DataContext.MenuItems

    where me.me_id == mi.me_id

    select mi).Count() > 0 ) //Boolean statement

    }).ToArray<Node>();

     

    But I get an error like this:

    "The query contains references to items defined on a different data context"

     

    How can I accomplish this?

     

    Many Thanks


    Friday, June 20, 2008 6:30 PM

Answers

  • I'm not sure why you see that error ... I attempted something similar (using Northwind), and it works:

     

     

    Code Snippet

        var q = (from o in db.Orders
                 where o.OrderDate > new DateTime(1900, 1, 1)
                 select new
                 {
                     Name = o.Customer.CompanyName,
                     HasChilds = (from od in db.OrderDetails
                                  where od.OrderID == o.OrderID
                                  select od).Count() > 0
                 }).ToArray();

     

     

     

    Can you check your code and confirm that you're indeed not mixing DataContext instances?

     

    Thanks,

     

    --Samir

     

     

    Monday, June 23, 2008 5:01 PM

All replies

  • I'm not sure why you see that error ... I attempted something similar (using Northwind), and it works:

     

     

    Code Snippet

        var q = (from o in db.Orders
                 where o.OrderDate > new DateTime(1900, 1, 1)
                 select new
                 {
                     Name = o.Customer.CompanyName,
                     HasChilds = (from od in db.OrderDetails
                                  where od.OrderID == o.OrderID
                                  select od).Count() > 0
                 }).ToArray();

     

     

     

    Can you check your code and confirm that you're indeed not mixing DataContext instances?

     

    Thanks,

     

    --Samir

     

     

    Monday, June 23, 2008 5:01 PM
  • Yes, I was... Thank you very much for checking.
     I had a DatabaseBase class that was always returning a new DataContext!!

    Very best.
    Alberto
    Wednesday, June 25, 2008 12:23 PM