我有一个gridview,其数据源是以下函数:
public static List<Train> GetTrainsByIDs(int [] ids) { using (var context = new MyEntities()) { return ids.Select(x => context.Trains.Single(y => y.TrainID ==x)).AsQueryable().Include(x=>x.Station).ToList(); } }
网格视图的ItemTemplate为<%#Eval(“Station.Name”)%>.
这会导致错误ObjectContext实例已被释放,并且不能再用于需要连接的操作,尽管我使用了include方法.
当我将功能更改为
public static List<Train> GetTrainsByIDs(int [] ids) { using (var context = new MyEntities()) { return context.Trains.Where(x => ids.Contains(x.TrainID)).Include(x=>x.Station).ToList(); } }
它工作正常,但后来它们出错的顺序,如果我有2个ID,我希望列表中有2个相同的列车.
解决方法
至于第一个查询:那是延迟执行.你创建了一个IEnumerable of Trains,注意到它没有Include方法,所以把它强制转换为IQueryable,添加Include并添加ToList()以防止延迟加载.
但是按照MSDN on DbExtensions.Include:
This extension method calls the Include(String) method of the IQueryable source object,if such a method exists. If the source IQueryable does not have a matching method,then this method does nothing.
(强调我的)
select的结果是IEnumerable转换为IQueryable,但现在由EnumerableQuery
实现,它没有实现Include.没有任何反应.
现在数据进入网格,试图显示工作站,在上下文消失时触发延迟加载.
除此之外,这个设计还有另一个缺陷:它分别为每个id激发一个查询.
所以第二个查询要好得多.这是一个查询,包括站点.但现在订单是由数据库喜欢返回的顺序决定的.您可以使用Concat解决此问题:
IQueryable<Train> qbase = context.Trains.Include(x=>x.Station); IQueryable<Train> q = null; foreach (var id in ids) { var id1 = id; // Prevent modified closure. if (q == null) q = qbase.Where(t => t.Id == id1); else q = q.Concat(qbase.Where (t => t.Id == id1)); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。