获取用户和角色时,EntityFramework和IdentityFramework会变慢

时间:2017-05-26 10:17:40

标签: c# entity-framework

我正在使用 EntityFramework ,而且大多数情况下都没问题。 我做了一些用户试验。当延迟加载被禁用时,用户将被检索并显示得非常快。

// Disable Lazy Loading
base.Configuration.LazyLoadingEnabled = false;

需要大约160毫秒才能撤回26个用户。 这很好,但我需要看到用户所属的角色声明。我可以保持延迟加载禁用并执行以下操作:

/// <summary>
/// Creates the User response model from the User model
/// </summary>
/// <param name="model">The User model</param>
/// <returns>A User response model</returns>
public UserViewModel Create(User model)
{

    // If we are null, return nothing
    if (model == null)
        return null;

    // Factorise our model
    return new UserViewModel
    {
        Id = model.Id,
        Department = model.Department,
        Disabled = model.Disabled,
        Email = model.Email,
        EmailConfirmed = model.EmailConfirmed,
        FirstName = model.FirstName,
        HasPassword = !string.IsNullOrEmpty(model.PasswordHash),
        HasTroposLogin = model.HasTroposLogin,
        LastName = model.LastName,
        LastLoginDate = model.LastLoginDate,
        UserName = model.UserName,
        UserImage = model.ProfileImageUri,

        DateCreated = model.DateCreated,
        DateModified = model.DateModified ?? DateTime.UtcNow,

        Roles = _userProvider.GetRolesAsync(model.Id).Result,
        Claims = _userProvider.GetClaimsAsync(model.Id).Result.ToList()
    };
}

在我的代码中,我可以这样做:

/// <summary>
/// Gets a list of Users
/// </summary>
/// <returns></returns>
public async Task<IList<UserViewModel>> ListAsync(int yield)
{

    // If we have a department get the users for that dept, otherwise get all users
    var users = await Users.ToListAsync();

    // Return our users
    return users.Select(UserFactory.Create).ToList();
}

但是这样做会将加载时间增加到大约5秒钟(对于26个用户!),这是不可接受的。 如果我启用 LazyLoading 并删除工厂:

/// <summary>
/// Gets a list of Users
/// </summary>
/// <returns></returns>
public async Task<IList<User>> ListAsync(int yield)
{

    // If we have a department get the users for that dept, otherwise get all users
    var users = await Users.ToListAsync();

    // Return our users
    return users.ToList();
}

大约需要4.5秒,但只能撤回角色ID,并且不会撤回任何声明。

所以我的问题是:

如何在不花大约5秒钟的情况下撤回所有用户,角色和声明?当然,我不是唯一经历过这种情况的人吗?

1 个答案:

答案 0 :(得分:1)

您应该查找Include方法,此方法使您可以在不延迟加载的情况下加载相关实体。

var usersWithList = users.include(u => u.Roles).include(u => u.Claims).ToList();