简体   繁体   中英

Null reference exception when querying the database

I'm using EF to query the database using the following code:

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

Whenever I try to use it, though, the damn thing crashes and gives me a null reference exception. Any ideas as to why? I know the command is properly formatted, but I'm not sure where else to check for errors; I'm very new to the MVC paradigm.

Here's the code for the model it's referencing, if it makes a difference:

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; }
    }


}

The call to FirstOrDefault() is most likely returning null (because a record wasn't found), and so when you try to access UserId you get that exception.

Select the field you want first, then perform the FirstOrDefault :

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

Now if no record is found, UserId will be null and you won't get that particular error.

i would recommend something like this. Here you have got a complete system to getting data from DB, by organized code. You will have your service which will be independence, and you will be able to add more "if" conditions based on what you want to extract.

////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; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM