繁体   English   中英

将ASP.Net Identity DbContext与我的DbContext合并

[英]Merging ASP.Net Identity DbContext with my DbContext

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

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

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

我在数据访问层项目中拥有的DB​​Context:

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

有一个更好的方法吗?

这已经在这里回答

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

如果您想举个例子,我之前已经完成了合并。 尽管它不是处​​于理想状态,但应作为您要实现的目标的一个示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM