2017-05-26 28 views
0

我正在使用EntityFramework並且大多數情況下沒有問題。 我已經對用戶做了一些嘗試。當延遲加載被禁用時,用戶被檢索並顯示得非常快。EntityFramework和IdentityFramework在獲取用戶和角色時速度較慢

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

拉回26位用戶大概需要160ms。 這很好,但我需要看到用戶所屬的角色索賠。我可以繼續延遲加載禁用,做這樣的事情:

/// <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用戶!)這是不能接受的。 如果我能惰性加載並刪除工廠:

/// <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

你應該尋找包含方法,這種方法給你posibility加載相關實體沒有延遲加載。

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