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 取出的数据是正确的.  杯具啊!

 

转载于:https://www.cnblogs.com/hezechang/archive/2010/07/10/1774716.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值