I have the following model:
public partial class User
{
// other properties
/// <summary>
/// Gets or sets user roles
/// </summary>
public virtual IList<UserRole> UserRoles
{
get => _userRoles ?? (_userRoles = UserUserRoleMappings.Select(mapping => mapping.UserRole).ToList());
}
/// <summary>
/// Gets or sets user-user role mappings
/// </summary>
public virtual ICollection<UserUserRoleMapping> UserUserRoleMappings
{
get => _userUserRoleMappings ?? (_userUserRoleMappings = new List<UserUserRoleMapping>());
protected set => _userUserRoleMappings = value;
}
}
在另一个库中提供服务的方法:
public virtual User GetUserByUsername(string username)
{
if (string.IsNullOrWhiteSpace(username))
return null;
var user = _dbContext.Users
.Where(u => u.Username == username)
.FirstOrDefault();
return user;
}
只有启用延迟加载时,它才能正常工作:
services.AddDbContext<DataContext>(options => options
.UseLazyLoadingProxies()
.UseSqlServer(connString));
如果未启用延迟加载,则用户属性不会被填充。 如果有人在未启用延迟加载的情况下尝试使用我的服务,我想抛出一个异常。如何做到这一点?我尝试检查属性
_dbContext.ChangeTracker.LazyLoadingEnabled
,但是这个属性总是为真,即使我没有启用延迟加载...