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 开发者_StackOverflow中文版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();
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;
}
}
You would need to manage the lifetime of your objectcontext for their proper initialization and disposal. For an excellent resource on context lifetime management, refer to http://blogs.msdn.com/b/alexj/archive/2009/05/07/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext.aspx
精彩评论