项目
版本

OpenIddict Entity Framework 6.x 集成

基本配置

为了配置 OpenIddict 使用 Entity Framework 6.x 作为应用程序、授权、范围和令牌的数据库,你需要:

  • 引用 OpenIddict.EntityFramework 包

    <PackageReference Include="OpenIddict.EntityFramework" Version="5.6.0" />
    
  • 创建一个从 DbContext 派生的数据库上下文,并在模型中注册 OpenIddict 实体

    public class ApplicationDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.UseOpenIddict();
        }
    }
    
  • 配置 OpenIddict 使用 Entity Framework 6.x 存储

    services.AddOpenIddict()
        .AddCore(options =>
        {
            options.UseEntityFramework()
                .UseDbContext<ApplicationDbContext>();
        });
    
  • 使用迁移或重新创建数据库以添加 OpenIddict 实体。更多信息,请阅读 代码优先迁移

高级配置

使用自定义主键类型

默认情况下,Entity Framework 6.x 整合使用 string 类型的主键,这与 ASP.NET Identity 使用的默认键类型相匹配。

与 Entity Framework Core 不同,Entity Framework 6.x 不支持封闭泛型类型,这阻止了在不子类化它们的情况下直接使用 OpenIddict 实体。因此,与 Entity Framework Core 相比,在 Entity Framework 6.x 中使用自定义主键类型稍微复杂一些,并且需要实现自定义实体,如下一节突出显示的那样。

使用自定义实体

对于需要在 OpenIddict 使用的属性之外存储额外数据的应用程序,可以使用自定义实体。为此,你需做以下操作:

  • 创建自定义实体

    public class CustomApplication : OpenIddictEntityFrameworkApplication<long, CustomAuthorization, CustomToken>
    {
        public string CustomProperty { get; set; }
    }
    
    public class CustomAuthorization : OpenIddictEntityFrameworkAuthorization<long, CustomApplication, CustomToken>
    {
        public string CustomProperty { get; set; }
    }
    
    public class CustomScope : OpenIddictEntityFrameworkScope<long>
    {
        public string CustomProperty { get; set; }
    }
    
    public class CustomToken : OpenIddictEntityFrameworkToken<long, CustomApplication, CustomAuthorization>
    {
        public string CustomProperty { get; set; }
    }
    
  • 调用泛型 ReplaceDefaultEntities() 方法强制 OpenIddict 使用自定义实体

    services.AddOpenIddict()
        .AddCore(options =>
        {
            // Configure OpenIddict to use the custom entities.
            options.UseEntityFramework()
                .UseDbContext<ApplicationDbContext>()
                .ReplaceDefaultEntities<CustomApplication, CustomAuthorization, CustomScope, CustomToken, long>();
        });
    
  • 在模型中注册自定义实体

    public class ApplicationDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.UseOpenIddict<CustomApplication, CustomAuthorization, CustomScope, CustomToken, long>();
        }
    }
    
在本文档中