Musaab Musaab -3 years ago 77
C# Question

EntityFramework Multiple Queries Multiple DataContexts? Multiple Connections?

I'm new to EF, and for the first time I need to execute multiple queries in the same time, lets say I have my BLL and DAL generated by EF, I also have a viewModel, on the BLL I'm referencing DAL and retrieve data like this:

public Decimal getPrice()
{
Decimal x = 0;
siliconContext = new DAL.Entities();
var result = from d in siliconContext.SILICONs
select d.MIN_PRICE;
foreach (Decimal d in result)
{
x = d;
}
return x;
}


all good, on the viewModel I use just this two lines of code:

Silicon sil = new Silicon();
Price = sil.getPrice();


I assumed that the Context will handle the connection, open the connection, do something and then close it, but now I'm in a situation where in my ViewModel I will reference two BLLs which they are going to reference two DALs and of course two different Contexts in the same method, who is going to manage this? is EF 4 is smart enough to open only one connection and let the two - or more - contexts to do their job and then close the connection? here is an example of how my viewModel will look like

Silicon sil = new Silicon();
Price = sil.getPrice();
Glass gl = new Glass();
GlassPrice = gl.getPrice();

Answer Source

First off you need to close the connection of the DataContext.

public Decimal getPrice()
{
    Decimal x = 0;
    using (DAL.Entities siliconContext = new DAL.Entities())
    {
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;
        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }
}

Secondly if you want to get data from two tables then do the following.

public Decimal getPrice()
{
    Decimal x = 0; 
    using (DAL.Entities siliconContext = new DAL.Entities())
    {
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;

        var result2 = from d in seliconContext.GLASEs
                      select d.MIN_PRICE;

        //You can then work with results from table GLASE!

        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download