简体   繁体   中英

Null AspNetUser using Entity Framework and Code First

I'm learning ASP.NET MVC 5 and I'm having trouble with Entity Framework. I'm doing code first with an existing database and I made some updates to my database structure so that my other tables use the ID in the AspNetUser table as the user ID. I think I've updated my database properly since it now shows up in Intellisense (I was previously using a custom user table), but for some reason I get a NullReferenceException when I run the following:

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        MarkContext x = new MarkContext();
        var y = x.courses.FirstOrDefault();
        foreach(var c in x.courses)
        {
            System.Diagnostics.Debug.WriteLine(c.courseCode + " " + c.courseTitle + " " + c.AspNetUser.Id);
        }
        return View();
    }

The null is found on the c.AspNetUser part of the query. Why would it be null if I've verified that the IDs are properly created? Is it possible that I need to use eager loading for this and, if so, how can I do that in this case?

Side Note: This is on the About() page that comes with a default MVC setup, so I haven't customized anything really besides this one method in the HomeController and the database itself.

you need to select the data after doing Eager loading as shown Here

then you can Select your value as::

   foreach(var c in x.courses.Include("AspNetUser"))
        {
            System.Diagnostics.Debug.WriteLine(c.courseCode + " " + c.courseTitle + " " + c.AspNetUser.Id);
        }

The problem ended up being that, somehow, there was a big block of trailing space inserted in the field that I was linking on in one of the tables. While SQL Server didn't acknowledge these spaces, this obviously caused problems with Entity Framework linking them. Removing the trailing spaces from the entries in that column with a simple RTRIM() fixed the issue.

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