请参阅下面的代码:
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 uquery中处理此问题?
您可以用.FirstOrDefault();
替换.ToList().Single();
。如果未找到,则application
将是null
。