查询数据库时出现空引用异常

时间:2014-07-28 23:55:53

标签: c# sql entity-framework asp.net-mvc-4

我正在使用EF使用以下代码查询数据库:

int UserId = db.StudentModel.FirstOrDefault(c => c.UserName == certUserName).UserId;

每当我尝试使用它时,该死的东西崩溃并给我一个空引用异常。任何想法为什么?我知道命令格式正确,但我不确定在哪里检查错误;我对MVC范例很陌生。

以下是它引用的模型的代码,如果它有所不同:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace IronGriffin.Models
{
    public class StudentModel
    {
        [Key]
        public int UserId { get; set; }
        public string UserName { get; set; }

        public virtual ICollection<Completion> Completions { get; set; }
    }


}

2 个答案:

答案 0 :(得分:5)

FirstOrDefault()的调用最有可能返回null(因为未找到记录),因此当您尝试访问UserId时,您会收到该异常。

首先选择您想要的字段,然后执行FirstOrDefault

int? UserId = db.StudentModel
                .Where(c => c.UserName == certUserName)
                .Select(c => c.UserId)
                .FirstOrDefault();

现在,如果未找到任何记录,UserId将为null,您将不会收到该特定错误。

答案 1 :(得分:0)

我会推荐这样的东西。 在这里,您有一个完整的系统,可以通过有组织的代码从DB获取数据。 您将获得独立的服务,并且您将能够添加更多&#34;如果&#34;基于您想要提取的条件。

////in your code
 var criteria = new CriteriaStudentModel({
      UserName = "Jack"    
 });
 var dto = SelectByName(criteria)
 if(dto.Count > 0)
  {
     var UserNamedJack = dto.FirstOrDefault();

  }




//you will call this method, which is going to call the SelectByCriteriaBase
public  List<StudentDto> SelectByName(CriteriaStudentModel criteria)
{
  var query = SelectByCriteriaBase(criteria);  //return you the query which was 
                                               //created by LINQ
  var dtos = query.Select(x=>x. new StudentDto
  {
     UserId = x.UserId,     //and put your data to a dto
     UserName = x.UserName,
     Completions = x.Completions
   }).ToList();
 return dtos;                          //after you can work with dto as you want

}
public IQuerable<StudentModel> SelectByCriteriaBase(CriteriaStudentModel criteria)
{

     var query = Query<StudentModel>();
     if(criteria.UserName !="")
     {
       query = query.Where(x=>x.UserName.Contains(criteria.UserName))
     }
     //here you can add more "if" sectors to organize better your code.
    return query; 
 }

public class StudentDto//DTO class which "holds" your data after inserting there
{                   //result from query
  public int UserId {get:set;}
  public string UserName {get:set;}
  public virtual ICollection<Completion> Completions { get; set; }

}