简体   繁体   中英

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.

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);

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