When I load a user using the User Manager
private UserManager<MyUser> GetUserManager()
{
var userStore = new UserStore<MyUser>(_context);
return new UserManager<MyUser>(userStore);
}
public MyUser GetUser(string username)
{
return GetUserManager().FindByName(username);
}
my UserAddress entity is populated, but my AddressType and Country entities in the UserAddress is null.
However using this to load a user and all entities are populated. All I do here is access the entities but don't do anything with them.
public MyUser GetUser(string username)
{
var addressTypes = _context.AddressType.ToList();
var countries = _context.Countries.ToList();
return GetUserManager().FindByName(username);
}
Also enabling lazy loading works like below.
public MyUser GetUser(string username)
{
_context.Configuration.LazyLoadingEnabled = true;
var user = GetUserManager().FindByName(username);
_context.Configuration.LazyLoadingEnabled = false;
return user;
}
So why are the entities null with lazy loading off but they work if I just access them in the context but do nothing with them?
I'm using DB First. Heres my entities (the important bits)
public class MyUser : IdentityUser
{
public MyUser()
{
this.Address = new List<UserAddress>();
}
public virtual IList<UserAddress> Address { get; set; }
}
[Table("AddressTypes")]
public partial class AddressTypes
{
public AddressTypes()
{
this.Address = new List<UserAddress>();
}
public int Id { get; set; }
public virtual IList<UserAddress> Address { get; set; }
}
[Table("Country")]
public partial class Country
{
public Country()
{
this.Address = new List<UserAddress>();
}
public int Id { get; set; }
public virtual IList<UserAddress> Address { get; set; }
}
[Table("UserAddress")]
public partial class UserAddress
{
public int Id { get; set; }
public string UserId { get; set; }
public int AddressTypeId { get; set; }
public int CountryId { get; set; }
public AddressTypes AddressType { get; set; }
public Country Country { get; set; }
[ForeignKey("UserId")]
public MyUser User { get; set; }
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…