Guillaume Lujan
Guillaume Lujan

Reputation: 79

ASP.NET MVC 5 IdentityUser related entity

I've the following ApplicationUser implementation :

public class ApplicationUser : IdentityUser
{
    public virtual Establishment Establishment { get; set; }
}

and the Establishment implementation :

public class Establishment
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<ApplicationUser> Users { get; set; }

    public virtual ICollection<Menu> Menus { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
}

An etablishment has many users but a user has only one establishment. I want to get the current establishment by the current user id :

var currentUserEstablishmentId = userManager
    .FindById(User.Identity.GetUserId()).Establishment.ID;

var establishment = db.Establishments
    .Single(e => e.ID == currentUserEstablishmentId);

But it throws me an error. the property Establishment of the currentUser is set to null.

How can i get the current Establishment of my current user ?

Thank you, Regards.

Upvotes: 0

Views: 1689

Answers (1)

Andy Refuerzo
Andy Refuerzo

Reputation: 3332

Have you tried adding the EstablishmentID on the ApplicationUser?

public class ApplicationUser : IdentityUser
{
    public virtual int EstablishmentID { get; set; }
    public virtual Establishment Establishment { get; set; }
}

Then your queries become:

var currentUser = userManager
    .FindById(User.Identity.GetUserId());

var establishment = db.Establishments
    .Single(e => e.ID == currentUser.EstablishmentID);

Upvotes: 3

Related Questions