LINQ - 无效的操作异常

时间:2016-07-17 19:41:57

标签: c# linq asp.net-mvc-4

请参阅以下代码:

static MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<DataObjects.Application, BusinessObjects.Application>();
        });

        public BusinessObjects.Application getApplication(string UserID)
        {
            using (CreditCardPreQualificationEntities CreditCardPreQualificationDatabase = new CreditCardPreQualificationEntities())
            {
                //DataObjects.Application application = CreditCardPreQualificationDatabase.Applications.FirstOrDefault(c => c.userID== UserID);
                BusinessObjects.Application application = CreditCardPreQualificationDatabase
                    .Applications
                    .ProjectTo<BusinessObjects.Application>(config)
                    .Where(c => c.UserID == UserID)
                    .ToList().Single();
                return application;
                //return new BusinessObjects.Application();
            }
        }

抛出invalidoperationexception,因为用户没有任何应用程序。我如何在LINQ uqery中处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

您可以将.ToList().Single();替换为.FirstOrDefault();。如果找不到,application将为null