我在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();
}
}
我在域/业务逻辑层中的Message类:
public class Message
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Body { get; set; }
[Required]
public DateTime Created { get; set; }
}
我在数据访问层项目中的DBContext:
public class PSNContext : DbContext, IPSNContext
{
public PSNContext()
:base ("DefaultConnection")
{
}
public DbSet<Message> Messages { get; set; }
}
将UI特定的代码从UI层中的ApplicationUser引入我的业务逻辑层是不对的:
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
有一个更好的方法吗?
1 回答
这已经回答here
关于将ApplicationUser移动到逻辑层,我个人认为这很好 . 那里的逻辑没有使用Web特定的命名空间 . 使用的是Microsoft.AspNet.Identity和System.Security.Claims相关 . 在这种情况下,ApplicationUser是实体,您的Web层应该使用ClaimsPrincipal进行身份验证和授权 .
如果你之前合并'd like an example, I' ve previously done this . 虽然它不是一个理想的状态,但它应该作为你想要达到的目标的一个例子 .