我在 Visual Studio 中使用默认的 ASP.Net MVC 模板。我正在使用在模板中为我创建的 ASP.Net 身份代码。我希望我使用的 DBContext 了解 ApplicationUser 实体(AspNetUser 表)与我的其余实体之间的关系。例如,我希望能够有一个 ApplicationUser.Messages 属性来展示 ApplicationUser 和 Message 实体之间的关系。我的 DbContext 用于数据访问层项目中的所有非身份实体。而模板 ApplicationDbContext 在 UI 层。为了保持身份实体和我的自定义实体之间的关系,我需要合并到一个 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();
}
}
我的域/业务逻辑层中的 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);
有更好的方法吗?
最佳答案
这已经被回答了here
关于把ApplicationUser移到逻辑层,我个人觉得可以。那里的逻辑不使用特定于 Web 的 namespace 。使用的是 Microsoft.AspNet.Identity 和 System.Security.Claims 相关的。在这种情况下,ApplicationUser 是实体,您的 Web 层应该使用 ClaimsPrincipal 进行身份验证和授权。
如果你想要一个例子,我有 previously done this合并之前。尽管它不处于理想状态,但它应该作为您要实现的目标的示例。
关于c# - 将 ASP.Net Identity DbContext 与我的 DbContext 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367976/