Remove all navigation property usage from EF Store

This commit is contained in:
Hao Kung 2014-12-19 13:26:54 -08:00
parent ac86d94eb6
commit 5d29d11ccb
5 changed files with 95 additions and 78 deletions

View File

@ -52,23 +52,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
b.ForRelational().Table("AspNetRoleClaims");
});
var userType = builder.Model.GetEntityType(typeof(TUser));
var roleType = builder.Model.GetEntityType(typeof(TRole));
var userClaimType = builder.Model.GetEntityType(typeof(IdentityUserClaim<TKey>));
var roleClaimType = builder.Model.GetEntityType(typeof(IdentityRoleClaim<TKey>));
var userRoleType = builder.Model.GetEntityType(typeof(IdentityUserRole<TKey>));
//var ucfk = userClaimType.GetOrAddForeignKey(userType.GetPrimaryKey(), new[] { userClaimType.GetProperty("UserId") });
//userType.AddNavigation(new Navigation(ucfk, "Claims", false));
//userClaimType.AddNavigation(new Navigation(ucfk, "User", true));
//var urfk = userRoleType.GetOrAddForeignKey(userType.GetPrimaryKey(), new[] { userRoleType.GetProperty("UserId") });
//userType.AddNavigation(new Navigation(urfk, "Roles", false));
//var urfk2 = userRoleType.GetOrAddForeignKey(roleType.GetPrimaryKey(), new[] { userRoleType.GetProperty("RoleId") });
//roleType.AddNavigation(new Navigation(urfk2, "Users", false));
var rcfk = roleClaimType.GetOrAddForeignKey(new[] { roleClaimType.GetProperty("RoleId") }, roleType.GetPrimaryKey());
roleType.AddNavigation("Claims", rcfk, false);
builder.Entity<IdentityUserRole<TKey>>(b =>
{
b.Key(r => new { r.UserId, r.RoleId });

View File

@ -59,11 +59,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
}
}
public virtual Task<TRole> GetRoleAggregate(Expression<Func<TRole, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
return Roles.FirstOrDefaultAsync(filter);
}
public async virtual Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
@ -163,7 +158,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var roleId = ConvertIdFromString(id);
return GetRoleAggregate(u => u.Id.Equals(roleId), cancellationToken);
return Roles.FirstOrDefaultAsync(u => u.Id.Equals(roleId), cancellationToken);
}
/// <summary>
@ -176,7 +171,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetRoleAggregate(u => u.Name.ToUpper() == name.ToUpper(), cancellationToken);
return Roles.FirstOrDefaultAsync(u => u.Name.ToUpper() == name.ToUpper(), cancellationToken);
}
private void ThrowIfDisposed()

View File

@ -72,14 +72,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
return AutoSaveChanges ? Context.SaveChangesAsync(cancellationToken) : Task.FromResult(0);
}
protected virtual Task<TUser> GetUserAggregate(Expression<Func<TUser, bool>> filter, CancellationToken cancellationToken = default(CancellationToken))
{
return Users.FirstOrDefaultAsync(filter, cancellationToken);
// TODO: .Include(u => u.Roles)
//.Include(u => u.Claims)
//.Include(u => u.Logins);
}
public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
@ -184,7 +176,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
var id = ConvertIdFromString(userId);
return GetUserAggregate(u => u.Id.Equals(id), cancellationToken);
return Users.FirstOrDefaultAsync(u => u.Id.Equals(id), cancellationToken);
}
public virtual TKey ConvertIdFromString(string id)
@ -215,7 +207,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.NormalizedUserName == normalizedUserName, cancellationToken);
return Users.FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName, cancellationToken);
}
public IQueryable<TUser> Users
@ -296,10 +288,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.RoleNotFound, roleName));
}
var ur = new IdentityUserRole<TKey> { UserId = user.Id, RoleId = roleEntity.Id };
// TODO: rely on fixup?
await UserRoles.AddAsync(ur);
user.Roles.Add(ur);
roleEntity.Users.Add(ur);
}
/// <summary>
@ -328,7 +317,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
if (userRole != null)
{
UserRoles.Remove(userRole);
user.Roles.Remove(userRole);
}
}
}
@ -339,7 +327,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
/// <param name="user"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@ -348,12 +336,11 @@ namespace Microsoft.AspNet.Identity.EntityFramework
throw new ArgumentNullException("user");
}
var userId = user.Id;
// TODO: var query = from userRole in UserRoles
var query = from userRole in user.Roles
var query = from userRole in UserRoles
join role in Roles on userRole.RoleId equals role.Id
where userRole.UserId.Equals(userId)
select role.Name;
//return await query.ToListAsync();
return Task.FromResult<IList<string>>(query.ToList());
return await query.ToListAsync();
}
/// <summary>
@ -371,7 +358,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
throw new ArgumentNullException("user");
}
if (String.IsNullOrWhiteSpace(roleName))
if (string.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, "roleName");
}
@ -380,9 +367,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
var userId = user.Id;
var roleId = role.Id;
return user.Roles.Any(ur => ur.RoleId.Equals(roleId));
//return await UserRoles.AnyAsync(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId));
//return UserRoles.Any(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId));
return await UserRoles.AnyAsync(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId));
}
return false;
}
@ -502,7 +487,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework
};
// TODO: fixup so we don't have to update both
await UserLogins.AddAsync(l);
user.Logins.Add(l);
}
public virtual async Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey,
@ -515,12 +499,10 @@ namespace Microsoft.AspNet.Identity.EntityFramework
throw new ArgumentNullException("user");
}
var userId = user.Id;
// todo: ensure logins loaded
var entry = await UserLogins.SingleOrDefaultAsync(l => l.UserId.Equals(userId) && l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
if (entry != null)
{
UserLogins.Remove(entry);
user.Logins.Remove(entry);
}
}
@ -532,11 +514,7 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
throw new ArgumentNullException("user");
}
// todo: ensure logins loaded
//IList<UserLoginInfo> result = user.Logins
// .Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.ProviderDisplayName)).ToList();
var userId = user.Id;
return await UserLogins.Where(l => l.UserId.Equals(userId))
.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.ProviderDisplayName)).ToListAsync();
}
@ -546,12 +524,11 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
// todo: ensure logins loaded
var userLogin = await
UserLogins.FirstOrDefaultAsync(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey);
if (userLogin != null)
{
return await GetUserAggregate(u => u.Id.Equals(userLogin.UserId), cancellationToken);
return await Users.FirstOrDefaultAsync(u => u.Id.Equals(userLogin.UserId), cancellationToken);
}
return null;
}
@ -638,9 +615,9 @@ namespace Microsoft.AspNet.Identity.EntityFramework
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
return GetUserAggregate(u => u.Email == email, cancellationToken);
return Users.FirstOrDefaultAsync(u => u.Email == email, cancellationToken);
// todo: ToUpper blows up with Null Ref
//return GetUserAggregate(u => u.Email.ToUpper() == email.ToUpper(), cancellationToken);
//return Users.FirstOrDefaultAsync(u => u.Email.ToUpper() == email.ToUpper(), cancellationToken);
}
/// <summary>

View File

@ -156,16 +156,90 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task EnsureRoleClaimNavigationProperty()
private async Task LazyLoadTestSetup(TestDbContext db, TUser user)
{
var context = CreateContext();
var roleManager = CreateRoleManager(context);
var r = CreateRole();
IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r));
var c = new Claim("a", "b");
IdentityResultAssert.IsSuccess(await roleManager.AddClaimAsync(r, c));
Assert.NotNull(r.Claims.Single(cl => cl.ClaimValue == c.Value && cl.ClaimType == c.Type));
var manager = CreateManager(context);
var role = CreateRoleManager(context);
var admin = CreateRole("Admin");
var local = CreateRole("Local");
IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo("provider", user.Id.ToString(), "display")));
IdentityResultAssert.IsSuccess(await role.CreateAsync(admin));
IdentityResultAssert.IsSuccess(await role.CreateAsync(local));
IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(user, admin.Name));
IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(user, local.Name));
Claim[] userClaims =
{
new Claim("Whatever", "Value"),
new Claim("Whatever2", "Value2")
};
foreach (var c in userClaims)
{
IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c));
}
}
[Fact]
public async Task LoadFromDbFindByIdTest()
{
var db = CreateContext();
var user = CreateTestUser();
await LazyLoadTestSetup(db, user);
db = CreateContext();
var manager = CreateManager(db);
var userById = await manager.FindByIdAsync(user.Id.ToString());
Assert.Equal(2, (await manager.GetClaimsAsync(userById)).Count);
Assert.Equal(1, (await manager.GetLoginsAsync(userById)).Count);
Assert.Equal(2, (await manager.GetRolesAsync(userById)).Count);
}
[Fact]
public async Task LoadFromDbFindByNameTest()
{
var db = CreateContext();
var user = CreateTestUser();
await LazyLoadTestSetup(db, user);
db = CreateContext();
var manager = CreateManager(db);
var userByName = await manager.FindByNameAsync(user.UserName);
Assert.Equal(2, (await manager.GetClaimsAsync(userByName)).Count);
Assert.Equal(1, (await manager.GetLoginsAsync(userByName)).Count);
Assert.Equal(2, (await manager.GetRolesAsync(userByName)).Count);
}
[Fact]
public async Task LoadFromDbFindByLoginTest()
{
var db = CreateContext();
var user = CreateTestUser();
await LazyLoadTestSetup(db, user);
db = CreateContext();
var manager = CreateManager(db);
var userByLogin = await manager.FindByLoginAsync("provider", user.Id.ToString());
Assert.Equal(2, (await manager.GetClaimsAsync(userByLogin)).Count);
Assert.Equal(1, (await manager.GetLoginsAsync(userByLogin)).Count);
Assert.Equal(2, (await manager.GetRolesAsync(userByLogin)).Count);
}
[Fact]
public async Task LoadFromDbFindByEmailTest()
{
var db = CreateContext();
var user = CreateTestUser();
user.Email = "fooz@fizzy.pop";
await LazyLoadTestSetup(db, user);
db = CreateContext();
var manager = CreateManager(db);
var userByEmail = await manager.FindByEmailAsync(user.Email);
Assert.Equal(2, (await manager.GetClaimsAsync(userByEmail)).Count);
Assert.Equal(1, (await manager.GetLoginsAsync(userByEmail)).Count);
Assert.Equal(2, (await manager.GetRolesAsync(userByEmail)).Count);
}
}
}

View File

@ -265,18 +265,6 @@ namespace Microsoft.AspNet.Identity.EntityFramework.Test
IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user));
}
[Fact]
public async Task EnsureRoleClaimNavigationProperty()
{
var context = CreateContext();
var roleManager = CreateRoleManager(context);
var r = new IdentityRole("EnsureRoleClaimNavigationProperty");
IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r));
var c = new Claim("a", "b");
IdentityResultAssert.IsSuccess(await roleManager.AddClaimAsync(r, c));
Assert.NotNull(r.Claims.Single(cl => cl.ClaimValue == c.Value && cl.ClaimType == c.Type));
}
[Fact]
public async Task AddUserToUnknownRoleFails()
{