加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 网格视图中的复杂对象

发布时间:2020-12-15 21:39:33 所属栏目:百科 来源:网络整理
导读:我有一个gridview,其数据源是以下函数: public static ListTrain 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()
我有一个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个相同的列车.

除了创建一个新的viewmodel之外,还有什么可以做的吗?感谢您的任何帮助

解决方法

至于第一个查询:那是延迟执行.你创建了一个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));
}

生成的查询不是很优雅(至少可以说),但毕竟它是一个查询而不是很多.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读