LinQ First和FirstOrDefault 问题

最近在使用linq 进行查询时发现在使用FirstOrDefault查询时源代码情况下出现正常数据,也不报错,而发布后则只会取到数据列表的第一个.代码如下:

var model = apps.Select(m => new AppViewListModel
                                             {
                                                 AppView = m,
                                                 AppViewUsed = useds.FirstOrDefault(x => x.AppView.Id == m.Id),
                                                 EcOrders = string.IsNullOrEmpty(m.App.ProductCode) ? null : User.Current.GetOrderList(m.App.ProductCode).ToList()
                                             });

发布后这样获取的model里面的AppViewUsed 全部都是useds 对象里面的第一个实例,但是源代码调试的时候不是,而是正常数据.

这个问题我查了好久都不知道为什么,因为源代码调试是正常的,发布后就不正常了.所以很郁闷啊~~~~

但是最后还是解决了 嘿嘿...     发现了FirstOrDefault 这个方法在根据条件查不出对象的话会取默认对象而不会给一个null值.

所以我的解决方法是:

 

            var model = new List<AppViewListModel>();
            foreach (var app in apps)
            {
                AppViewListModel viewListModel = new AppViewListModel();
                viewListModel.AppView = app;
                if (app != null)
                {
                    try
                    {
                        viewListModel.AppViewUsed = User.Current.Page.AppViews.Where(m => m.Status == UsedStatus.Normal && m.AppView.Id == app.Id).First();
                    }
                    catch (Exception)
                    {

                        viewListModel.AppViewUsed = null;
                    }


                    viewListModel.EcOrders = string.IsNullOrEmpty(app.App.ProductCode)
                                                 ? null
                                                 : User.Current.GetOrderList(app.App.ProductCode).ToList();
                }
                model.Add(viewListModel);
            }

这样就把简单的代码写成了这样了,不知道谁有更好的解决方法!!!  

至今还困惑的是为什么在源代码的时候FirstOrDefault 取出的数据是正确的.  杯具啊!

 

posted @ 2010-07-10 09:21  HEZECHANG  阅读(7437)  评论(0编辑  收藏  举报