我一直在這個背後摸不着頭腦,但仍然無法弄清楚可能會導致這種情況。Linq to SQL使用存儲庫模式:對象沒有支持轉換到SQL
我有一個複合存儲庫對象引用兩個其他存儲庫。我想在我的LINQ查詢中實例化Model類型(請參閱第一個代碼片段)。
public class SqlCommunityRepository : ICommunityRepository {
private WebDataContext _ctx;
private IMarketRepository _marketRepository;
private IStateRepository _stateRepository;
public SqlCommunityRepository(WebDataContext ctx, IStateRepository stateRepository, IMarketRepository marketRepository)
{
_ctx = ctx;
_stateRepository = stateRepository;
_marketRepository = marketRepository;
}
public IQueryable<Model.Community> Communities
{
get
{
return (from comm in _ctx.Communities
select new Model.Community
{
CommunityId = comm.CommunityId,
CommunityName = comm.CommunityName,
City = comm.City,
PostalCode = comm.PostalCode,
Market = _marketRepository.GetMarket(comm.MarketId),
State = _stateRepository.GetState(comm.State)
}
);
}
}
}
說我傳遞模樣的資源庫對象本
public class SqlStateRepository : IStateRepository {
private WebDataContext _ctx;
public SqlStateRepository(WebDataContext ctx) { _ctx = ctx; }
public IQueryable<Model.State> States
{
get
{
return from state in _ctx.States
select new Model.State()
{
StateId = state.StateId,
StateName = state.StateName
};
}
}
public Model.State GetState(string stateName)
{
var s = (from state in States
where state.StateName.ToLower() == stateName
select state).FirstOrDefault();
return new Model.State()
{
StateId = s.StateId,
StateName = s.StateName
};
}
和
public class SqlMarketRepository : IMarketRepository {
private WebDataContext _ctx;
public SqlMarketRepository(WebDataContext ctx)
{
_ctx = ctx;
}
public IQueryable<Model.Market> Markets
{
get
{
return from market in _ctx.Markets
select new Model.Market()
{
MarketId = market.MarketId,
MarketName = market.MarketName,
StateId = market.StateId
};
}
}
public Model.Market GetMarket(int marketId)
{
return (from market in Markets
where market.MarketId == marketId
select market).FirstOrDefault();
}
}
這是我如何接線這一切:
WebDataContext ctx = new WebDataContext();
IMarketRepository mr = new SqlMarketRepository(ctx);
IStateRepository sr = new SqlStateRepository(ctx);
ICommunityRepository cr = new SqlCommunityRepository(ctx, sr, mr);
int commCount = cr.Communities.Count();
上面代碼片段的最後一行是失敗的地方。當我通過實例化(new Model.Community)進行調試時,它永遠不會進入任何其他存儲庫方法。這三個對象背後的底層表之間沒有關係。這是否會成爲LINQ to SQL無法正確構建表達式樹的原因?
這樣做。它不會觸發查詢,直到你調用IQueryable上的方法? – Praveen 2010-08-03 18:30:51
大多數Linq方法都是延遲的 - 直到枚舉結果纔會評估查詢。 foreach和ToList都是枚舉查詢的手段。 – 2010-08-03 23:13:19