[英]Using UnitOfWork Pattern With Compiled Queries
我正在嘗試使用工作單元設計模式在我的項目中設置一些已編譯的查詢。 這些查詢在某些請求期間會多次重用,使它們成為已編譯的查詢有助於極大地加快應用程序的速度。 我注意到的一件事是,我必須傳遞我正在使用的數據上下文,而不是能夠使用在工作單元類中設置的存儲庫。
這是有效的方法:
private static Func<PivotalDataContext, Binary, Binary, Int32?, IQueryable<Location>> GetLocationFunc
{
get
{
Func<PivotalDataContext, Binary, Binary, Int32?, IQueryable<Location>> func =
CompiledQuery.Compile(
(PivotalDataContext db, Binary destCityId, Binary stateId, Int32? cityNeoId) =>
(
(from cityDest in db.Destination_Cities
where
cityDest.Destination_City_Id == destCityId || cityDest.Neo_Id == cityNeoId
join destCountry in db.Destination_Countries
on cityDest.Destination_Country_Id equals destCountry.Destination_Country_Id into country
from destCountry in country.DefaultIfEmpty()
join destCont in db.Destination_Continents
on destCountry.Destination_Continent_Id equals destCont.Destination_Continent_Id into continent
from destCont in continent.DefaultIfEmpty()
select new Location
{
CityName = destCity.Name,
CountryName = destCountry.Name,
ContinentName = destContinent.Name
})));
return func;
}
}
這是我想要的:
構造函數:
private static IRepository<Destination_Country> _destCountryRepo;
private static IRepository<Destination_Continent> _destContinentRepo;
private static IRepository<Destination_City> _destinationCityRepo;
public LocationService()
{
_destCountryRepo = UnitOfWork.DestCountryRepo;
_destCityRepo = UnitOfWork.DestCityRepo;
_destContinentRepo = UnitOfWork.DestContinentRepo;
_destCountryRepo = UnitOfWork.DestCountryRepo;
}
這是編譯后的查詢(我已將對數據表的調用從datacontext替換為在構造函數中設置的表):
private static Func<PivotalDataContext, Binary, Binary, Int32?, IQueryable<Location>> GetLocationFunc
{
get
{
Func<PivotalDataContext, Binary, Binary, Int32?, IQueryable<Location>> func =
CompiledQuery.Compile(
(PivotalDataContext db, Binary destCityId, Binary stateId, Int32? cityNeoId) =>
(
(from cityDest in _destCityRepo.Table
where
cityDest.Destination_City_Id == _destCityId || cityDest.Neo_Id == cityNeoId
join destCountry in _destCountryRepo.Table
on cityDest.Destination_Country_Id equals destCountry.Destination_Country_Id into country
from destCountry in country.DefaultIfEmpty()
join destCont in _destContinentRepo.Table
on destCountry.Destination_Continent_Id equals destCont.Destination_Continent_Id into continent
from destCont in continent.DefaultIfEmpty()
select new Location
{
CityName = destCity.Name,
CountryName = destCountry.Name,
ContinentName = destContinent.Name
})));
return func;
}
}
當我嘗試使用在UnitOfWork類中設置的表並在編譯后的查詢中創建斷點時,由於某些原因,即使這些表是在創建類時設置的,這些表仍為null。 是否有可能做到這一點? 還是編譯后的查詢始終需要傳入數據上下文?
提前致謝!
簡短的回答:是的,您必須將其傳遞。
代碼的結構方式是,您將提供DataContext
以及其他參數以執行查詢。 因為您將其掛在靜態屬性之外,所以始終必須傳遞DataContext
因為它不是靜態的。
但是,即使您是在非靜態上下文中創建查詢的,也沒有在適當的情況下可以創建和使用DataContext
條件與查詢一樣長。 您將獲得一個長期存在的DataContext
,這不是它打算被使用的方式,並且引入了許多問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.