Click here to Skip to main content
15,922,427 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have (one to many) relation between 2 tables, when im trying to retrieve the value of a column in the 2nd table it throw null exception:

item.V_DriversVM.Name = 'item.V_DriversVM.Name' threw an exception of type 'System.NullReferenceException'


What I have tried:

here is my code:

Model 1:
C#
public class DriverViewModel
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DriverId { get; set; }

    [Required(ErrorMessage = "Driver name is required")]
    [DisplayName("Driver Name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Mobile No. is required")]
    [DataType(DataType.PhoneNumber)]
    [DisplayName("Mobile No.")]
    public string Mobile { get; set; }

    [Required(ErrorMessage = "Email address is required")]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    public string Email { get; set; }

    public virtual ICollection <dutyviewmodel> Duties { get; set; }
}

Model 2:
C#
public class DutyViewModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DutyId { get; set; }

    [DisplayName("Description")]
    [Required(ErrorMessage = "Description is required")]
    public string Desc { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Required(ErrorMessage = "Date is required")]
    public DateTime? Date { get; set; }

    [DisplayName("Start Time")]
    [DataType(DataType.Time)]
    [Required(ErrorMessage = "Start time is required")]
    public DateTime? StartTime { get; set; }

    [DisplayName("End Time")]
    [DataType(DataType.Time)]
    [Required(ErrorMessage = "End time is required")]
    public DateTime? EndTime { get; set; }

    [Required]
    [DisplayName("Driver")]
    public int DriverId { get; set; }

    
    [ForeignKey("DriverId")]
    public virtual DriverViewModel V_DriversVM { get; set; }
}

Controller:
C#
private MyDbContext _context = new MyDbContext();
 
public ActionResult Index(string SearchString, string sortBy)
 {
     var duties = _context.Duties.Include(i => i.DriverId);
     if (!String.IsNullOrEmpty (SearchString ))
     {
         duties = duties.Where(n=> n.Date.ToString () == SearchString) ;
     }
     
     return View(duties.ToList ());
 }

Index View:
CSHTML
@foreach (var item in Model)
 {
                           @Html.DisplayFor(modelItem => item.Desc)
                               @Html.DisplayFor(modelItem => item.Date)
                               @Html.DisplayFor(modelItem => item.StartTime)
                               @Html.DisplayFor(modelItem => item.EndTime)
                               @Html.DisplayFor(modelItem =>  item.V_DriversVM.Name)
               }

error on this line: @Html.DisplayFor(modelItem => item.V_DriversVM.Name)

please assist. thanks
Posted
Updated 19-May-24 23:22pm
v2

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Quote:
C#
var duties = _context.Duties.Include(i => i.DriverId);
The Include method needs the path to the navigation property to include:
Eager Loading of Related Data - EF Core | Microsoft Learn[^]

You have passed in the path to the foreign key property by mistake.

Change that line to:
C#
var duties = _context.Duties.Include(i => i.V_DriversVM);
 
Share this answer
 
Comments
Member 10563482 22-May-24 11:22am    
i've tried didnt work too..
Richard Deeming 23-May-24 3:25am    
"Didn't work" is probably the most useless thing anyone can say. Imagine a user of your application phoned up, said "Your program didn't work!", and promptly hung up - how long would you spend trying to fix their problem based on that error report?

If the user can't be bothered to provide any details of the problem, then why should you spend any time trying to solve it for them?
item.V_DriversVM is probably null, check it using if inline statement, and if there is no data, so display watever you want, else then display the name.
C#
Try:
@foreach (var item in Model)
 {
                           @Html.DisplayFor(modelItem => item.Desc)
                               @Html.DisplayFor(modelItem => item.Date)
                               @Html.DisplayFor(modelItem => item.StartTime)
                               @Html.DisplayFor(modelItem => item.EndTime)
                               @Html.DisplayFor(modelItem =>  item.V_DriversVM == null ? "No Data" : item.V_DriversVM.Name
               } 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900