Cannot retrieve inherited custom property value from AspNetUsers table

一笑奈何 提交于 2019-12-08 06:33:46

问题


I use ASP.NET Identity 2.0 and create two different user entities inherited from ApplicationUser as posted on Implementing Inheritance with the Entity Framework 6 in an ASP.NET MVC 5 but I cannot reach these custom properties and its values (StudentNumber and Profession) while reaching custom properties defined in ApplicationUser (Name, Surname). And idea?

Here is the code I tried to use for retrieving value Name, Surname, StudentNumber and Profession:

Controller:

public AccountController(ApplicationUserManager userManager, 
    ApplicationSignInManager signInManager)
{
    UserManager = userManager;
    SignInManager = signInManager;
}

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext()
            .GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}


[AllowAnonymous]
public ActionResult ListAccount(JQueryDataTableParamModel param)
{
    var allUsers = UserManager.Users;
    //code omitted for brevity

    /* as there is no property StudentNumber and Profession in Users, 
    I cannot reach these properties while reaching other custom properties */ 
    var result = from c in allUsers 
select new[] { Convert.ToString(c.Id), c.Name, c.Surname, c.Email, c.PhoneNumber };
 }

Models:

public abstract class ApplicationUser : IdentityUser
{
    //snip
    //Common properties
    public string Name { get; set; }
    public string Surname { get; set; }
}

I defined different type classes and inherited from the base class:

public class StudentUser : ApplicationUser
{
    public string StudentNumber { get; set; }
}

public class ProfessorUser : ApplicationUser
{
    public string Profession { get; set; }
}

回答1:


When creating a list of variables created from varying classes from a base class you are only going to be able to access the attributes from the base class.

If you create a list of one object type only, then yes you can access the added attributes of that inherited class e.g. for StudentUser, you will be

List<StudentUser> students, you will be able to access the StudentNumbers from these items.

There's not much you can do if you are wanting to grab a list from the base class to catch all Users. You can only get the attributes from that list that are common to all classes in the list.

For populating a view with varying classes, some condition testing for class type would do to populate the attribute specific to that class.

For e.g.

if(usertype == Student)
    room = user.Room;


来源:https://stackoverflow.com/questions/39179146/cannot-retrieve-inherited-custom-property-value-from-aspnetusers-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!