默认的MVC 5 App附带了IdentityModels.cs中的这段代码 - 这段代码用于默认模板的所有ASP.NET Identity操作:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用带有Entity Framework的视图构建一个新控制器并在对话框中创建一个"新数据上下文...",我会为我生成这个:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class AllTheOtherStuffDbContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// …
Run Code Online (Sandbox Code Playgroud) asp.net asp.net-mvc entity-framework asp.net-mvc-5 asp.net-identity
IdentityDbContext似乎有很多混乱.
如果我们在应用程序中创建两个数据库上下文,一个用于Identity,一个用于我们的自定义业务数据,则Identity Database Context继承自IdentityDbContext,而我们的自定义业务数据继承自DbContext.
所以让我们将以下内容添加到控制器:
private MyDbContext db = new MyDbContext();
private ApplicationDbContext identityDb = new ApplicationDbContext();
Run Code Online (Sandbox Code Playgroud)
以下是控制器中的Index方法:
var thingsInMyBusinessDb = db.Things.ToList();
var usersInIndentityDb = identityDb.AspNetUsers.ToList(); // THIS WILL HAVE AN ERROR
var roles = identityDb.AspNetRoles.ToList(); // ERROR
Run Code Online (Sandbox Code Playgroud)
您还会注意到Indentity数据库中的表不可用.为什么是这样?
目前从2.0.0-beta1开始,有一个用户和角色项目,但我希望实际的表格可用. 那么为何不?如果我想访问AspNetUserRoles怎么办?
当然,如果它被视为实体框架中的任何数据库上下文,那么Asp.Net Identity的许多混淆和问题肯定会消失.
我在Visual Studio中使用默认的ASP.Net MVC模板.我正在使用在模板中为我创建的ASP.Net Identity代码.我想用DBContext来了解ApplicationUser实体(AspNetUser表)和其他实体之间的关系.例如,我希望能够拥有一个ApplicationUser.Messages属性,该属性展示了ApplicationUser和Message实体之间的关系.我有一个数据访问层项目中所有非身份实体的DbContext.模板ApplicationDbContext位于UI层中.为了保持Identity实体和我的自定义实体之间的关系,我需要合并到一个DbContext中,对吗?我该怎么做呢?
以下是我的一些示例代码:
使用我的自定义Messages属性从MVC模板在UI Layer项目中为我创建的IdentityUser和DbContext:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public ICollection<Message> Messages { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Run Code Online (Sandbox Code Playgroud)
我在域/业务逻辑层中的Message类:
public class …
Run Code Online (Sandbox Code Playgroud)