我一直在这个背后摸不着头脑,但仍然无法弄清楚可能会导致这种情况。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