【问题标题】:Merging ASP.Net Identity DbContext with my DbContext将 ASP.Net Identity DbContext 与我的 DbContext 合并
【发布时间】:2016-07-21 22:44:45
【问题描述】:

我在 Visual Studio 中使用默认的 ASP.Net MVC 模板。我正在使用在模板中为我创建的 ASP.Net 身份代码。我希望我使用的 DBContext 了解 ApplicationUser 实体(AspNetUser 表)与我的其他实体之间的关系。例如,我希望能够有一个 ApplicationUser.Messages 属性来展示 ApplicationUser 和 Message 实体之间的关系。我的 DbContext 用于数据访问层项目中的所有非身份实体。模板 ApplicationDbContext 位于 UI 层中。为了保持 Identity 实体和我的自定义实体之间的关系,我需要合并到一个 DbContext 中,对吗?我该怎么做呢?

这是我所拥有的一些示例代码:

在 UI 层项目中使用我的自定义 Messages 属性从 MVC 模板为我创建的 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();
    }
}

我的域/业务逻辑层中的消息类:

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);

有没有更好的方法来做到这一点?

【问题讨论】:

  • 这个问题是对的。我面临同样的问题。我不想维护两个 DbContexts ,一个在 UI 层,另一个在我的 DataAccess 层。如果我将 ASP.NET 标识类移动到 DataLayer,我必须将 System.AspNet.Identity 命名空间也移动到 DataLayer,并且我希望我的数据层独立于 UI 技术。在数据层中有命名空间“AspNet”是否正确?

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

这个问题已经回答here

关于将 ApplicationUser 移到逻辑层,我个人认为很好。那里的逻辑不使用特定于 Web 的名称空间。使用的是 Microsoft.AspNet.Identity 和 System.Security.Claims 相关的。在这种情况下 ApplicationUser 是实体,您的 Web 层应该使用 ClaimsPrincipal 进行身份验证和授权。

如果你想要一个例子,我之前有 previously done this 合并。尽管它不是处​​于理想状态,但它应该作为您尝试实现的目标的示例。

【讨论】:

    最近更新 更多