简体   繁体   中英

How to add a user to a model to display on web page

I am making an application where users are given the ability to make a quiz. Below is a sample model of the quiz class:

[Table("Quizzes")]
public class Quiz
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User CreatedBy { get; set; }
}

The "User" class, so far, only defines an Id and UserName:

[Table("Users")]
public class User
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

In my View, I want to display a list of Quizzes and their created User. Here is the portion of the view that does that:

@foreach(var item in Model)
{
    <div>@item.Name</div>
    <div>@item.CreatedBy.UserName</div>
    <hr />
}

When I go to run the program, I get an error: Object reference not set to an instance of an object.

I know I am doing something very wrong, something very simple, but I can't put my thumb on it and I haven't been able to find a solution to my problem elsewhere. Can anyone help?

UPDATE:

Here is the full error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web   
request. Please review the stack trace for more information about the error and where 
it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an 
instance of an object.

Source Error:


Line 25: {
Line 26:     <div>@item.Name</div>
Line 27:     <div>@item.CreatedBy.UserName</div>
Line 28:     <hr />
Line 29: }


Source File: \Views\Home\Index.cshtml    Line: 27 

Controller:

public class HomeController : Controller
{

    YouGotQuizzedDb _db = new YouGotQuizzedDb();

    public ActionResult Index()
    {
        var model = _db.Quizzes.ToList();

        return View(model);
    }
}
var model = _db.Quizzes.ToList();

that is where your problem is. When you return a list of Quiz zes, triggered by the ToList() , the User object is not returned with it. You should be eager loading the User object. You should do something like:

var model = _db.Quizzes.Include(x => x.CreatedBy).ToList();

if the above doesn't work (I forgot if you need an extension method using that or not) you can try this, which will give you the same result

var model = _db.Quizzes.Include("CreatedBy").ToList();

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