Passage
Passage

Reputation: 234

MVC - Unable to Reference Items from dbContext

I have a View called EventDetails, called with the following:

    public IActionResult EventDetails(int eID)
    {
        var events = context.Events;
        Event e = new Models.Event();
        foreach (Event i in events)
        {
            if (i.EventID.Equals(eID)) { e = i; }
            Console.WriteLine(eID + "   " + i.EventID);
        }
        ViewBag.isYours = false;
        if (e.Artist.Equals(userManager.GetUserAsync(HttpContext.User)))
        {
            ViewBag.isYours = true;
        }
        return View();
    }

context is an ApplicationDbContext, which includes DbSets of Genres, Events, and ApplicationUsers. EventDetails is called with <a asp-action="EventDetails" asp-controller="Home" [email protected]>@anEvent.EventName</a> where anEvent is an element of an IEnumerable set of Events. (Passed in as ex ".../Home/EventDetails/2".)

When EventDetails is called, it seems that eID is left empty, as it does not appear in the Autos window with other items. Similarly, context.Events does not display any records in the Autos window.

What is the most likely cause of these errors?

screenshot

Upvotes: 0

Views: 58

Answers (1)

Klinger
Klinger

Reputation: 4970

You are using the async version of getuser userManager.GetUserAsync(HttpContext.User) and it is returning before it has a chance to get the result for you.

Either change it to the synchronous version or use await userManager.GetUserAsync(HttpContext.User).

I think what you really want is something along the lines of the following:

public async IActionResult EventDetails(int eID)
{
    Event model = new Models.Event();
    var event = context.Events.Include(evt => evt.Artist)
                              .FirstOrDefault(evt => evt.EventID = eID);
    if (event == null) 
    {
       // return error
    }
    else
    {
       ViewBag.isYours = false;
       var user = await userManager.GetUserAsync(HttpContext.User);
       if (user == null)
       {
          // return error
       }
       if (event.Artist.SomeProperty == user.SomeProperty)
       {
           ViewBag.isYours = true;
           // Populate `model` properties with data from `event`
       }
    }
    return View(model);
}

Upvotes: 1

Related Questions