Custom entities with asp net identity (one-to-many)

前端 未结 1 828
甜味超标
甜味超标 2020-12-20 02:03

When I load a user using the User Manager

private UserManager GetUserManager()
{
    var userStore = new UserStore(_context);
            


        
相关标签:
1条回答
  • 2020-12-20 02:44

    You've kind of answered your own Question here. With Lazy Loading, the database is re-queried for the requested information when you access it using the dot notation. So in your example accessing user.AddressType would actually make another request to the DB to get the AddressType associated to that user and store it in the Context.

    With Lazy Loading turned off, and you querying the DB for the AddressTypes and Countries, you are pulling then into the DbContext so when you access the related information i.e.user.AddressType, the AddressType for that user is already loaded into the DbContext, so it will use that and not have to requery the database. without prefetching them, they will always be a null.

    If you always want to bring in those related tables, then you will need to modify your query to use the .Include() method. For this you will need to derive from UserStore and override the FindByName method like so.

    public class MyUserStore : UserStore<MyUser>
    {
        public MyUserStore(DbContext context) : base(context)
        {
        }
    
        public override MyUser FindByName(string userName)
        {
            return Users.Include(x=>x.AddressType).Include(x=>x.Country).FirstOrDefault(n=>n.UserName == userName); 
            //you may need to also include the following includes if you need them
            //.Include(x=>x.Roles).Include(x=>x.Claims).Include(x=>x.Logins)
        }
    }
    

    then use this new Store in your UserManager

    private MyUserManager GetUserManager()
    {
        var userStore = new MyUserStore(_context);
        return new UserManager<MyUser>(userStore);
    }
    
    0 讨论(0)
提交回复
热议问题