0

I have two models:

ApplicationUsers: ( The default that comes with Identity framework )

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

and Room:

public class Room
{
    public int Id { get; set; }
    public string RoomName { get; set; }
    public ApplicationUser User1 { get; set; }
    public ApplicationUser User2 { get; set; }
    public ApplicationUser User3 { get; set; }
}

I created a new user at AppliactionUser:

ApplicationUsers table And I manually added a new Room and reference to that User:

Rooms Table

NOTE: It might not seem from the images, but their ids are the same, I doubled-checked it, the reason it looks different in these pictures is because there's not enough space to display the full length.

But when I ran my web and wrote this code on Home Controller :

public class HomeController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();
    public ActionResult Index()
    {
        var varForDebug = db.Rooms.Find(1); // Room id 1

        return View();
    }

and made a breaking point at varForDebug I couldn't see an ApplicationUser at User1:

enter image description here

Why is that and how it could be solved?

Note: I'm using: ASP.NET MVC Web Application (.NET Framework ) 4.6.1 with Identity.

Note2: Include wants only string parameter from some reason, whys that?

Maybe I should consider adding Room property to ApplicationUser?

Dorki
  • 777
  • 1
  • 6
  • 16
  • 2
    Either enable lazy loading and make those properties virtual or follow the below answer about calling Include for each relationship you need to load like `Include("propertyname")` – Mat J Aug 25 '19 at 16:29

2 Answers2

2

First, add the references:

using System.Linq;

and

using System.Data.Entity;

If you want to keep using the Find operation, use:

 var varForDebug = db.Rooms.Find(1); // Room id 1 `

 // Load the user 
 context.Entry(varForDebug).Reference(p => p.User1).Load();

or

db.Rooms.Include(r => r.User1).FirstOrDefault(x=>x.Id==1);
David Donari
  • 549
  • 5
  • 15
1

Use db.Rooms.Include(r => r.User1).FirstOrDefault(r => r.Id == 1);

and repeat that for User2, User3 etc.

Henk Holterman
  • 250,905
  • 30
  • 306
  • 490