【问题标题】:Creating a DbContext Interface with EF6 and Identity使用 EF6 和 Identity 创建 DbContext 接口
【发布时间】:2019-10-16 13:59:20
【问题描述】:

我想为我的 ApplicationDbContext 创建一个接口。但是,它继承自 IdentityDbContext。

 public class ApplicationDbContext
        : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IDbContext

目前,IDbContext 没有对 IdentityDbContext 表(例如用户、角色等)的任何引用...因此,当我在代码中使用该接口时,任何访问身份表的操作都将不起作用,因为该接口没有t包括那些。我尝试添加一个

IDbSet<ApplicationUser> 

到我的 ApplicationDbContext 以便我可以在界面中引用它,但它会变得令人困惑,因为 ApplicationUser 是 IdentityUser 的自定义实现。如何创建此接口,以便我可以通过该接口引用我的 ApplicationDbContext 可以访问的所有表?

【问题讨论】:

  • 你的意思是像DbSet&lt;ApplicationUser&gt; Users { get; set; }在你的界面?
  • 是的。哇,我是不是想多了?

标签: entity-framework dependency-injection entity-framework-6 asp.net-identity dbcontext


【解决方案1】:

您只需要复制界面中的属性。例如:

public interface IDbContext
{
    IDbSet<ApplicationUser> Users { get; set; }
    IDbSet<ApplicationRole> Roles { get; set; }
    // etc
}

您还可以抽象接口以使其与 Identity 对象更直接兼容:

public interface IDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>
    where TUser : IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim>
    where TRole : IdentityRole<TKey, TUserRole>
    where TUserLogin : IdentityUserLogin<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserClaim : IdentityUserClaim<TKey>
{ 
    IDbSet<TUser> Users { get; set; }
    IDbSet<TRole> Roles { get; set; }
    // etc
}

并调整你的上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>,
    IDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>

【讨论】:

  • 所以当我添加这个时,它说我没有实现 IDbContext.Users:“IdentityContext 无法实现 IDbContext 用户,因为它没有匹配的返回类型 DbSet
  • 'ApplicationDbContext' 没有实现接口成员 'IDbContext.Roles'。 'IdentityDbContext.Roles' 无法实现 'IDbContext.Roles',因为它没有匹配的返回类型 'DbSet '.
  • 另外:“ApplicationDbContext”没有实现接口成员“IDbContext.Users”。 'IdentityDbContext.Users' 无法实现 'IDbContext.Users' 因为它没有匹配的返回类型 'DbSet '.
  • 您使用的是 IDbSet 而不是 DbSet?
  • 不,应该吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多