none
Is there a way to join across dbcontexts in entity framework? RRS feed

  • Question

  • I am working on an OData project that requires me to join tables from different context(s) using EF. 

    i want to use EF to work with multiple contexts, and join on them to allow OData expands. I need to be able to connect to the tables in their respective database instances and ensure all OData functionality is preserved (expanding, sorting, filtering).

    An example would be something like this:

            public static IEnumerable<Products> GetProducts(decimal key)
            {
                var db = new Entities();
                var entities = db.ProductCategory.Where(x => x.ProductCategoryID == key)
                    .SelectMany(x => x.Products);
                return entities;
            }


    where the ProductCategory is in one context and Products in a different context. the key is the CategoryID which I will get from the ProductCategory table. Once I have that ID, I would then go to the Products table to grab all products in that category.



    What I have seen is the suggestion to bring the data in memory and then use IQueryable or IEnumerable in joining the tables and working with the data. In my case, I want OData to handle the magic.
    Friday, November 20, 2015 4:17 PM

Answers

All replies

  • If I recall, you cannot join across DBcontexts.
    Sunday, November 22, 2015 12:16 AM
  • Hello Lungisa,

    >>What I have seen is the suggestion to bring the data in memory and then use IQueryable or IEnumerable in joining the tables and working with the data. In my case, I want OData to handle the magic.

    Cross join is supported showed as below:

    var crossJoin = from a in context.TableA.AsEnumerable()
                    from b in context2.TableB.AsEnumerable()
                    select new
                    {
                      a,
                      b
                    };

    but cross context or cross database linq-to-entities queries are not supported.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, November 24, 2015 2:22 AM
    Moderator