Entity Framework
基本配置
要将 OpenIddict 配置为使用 Entity Framework 6.x 作为应用程序、授权、范围和令牌的数据库,您需要:
参考
OpenIddict.EntityFramework
包:<PackageReference Include="OpenIddict.EntityFramework" Version="3.1.1" />
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 实体。有关更多信息,请阅读代码优先迁移。
高级配置
Use a custom primary key type
By default, the Entity Framework 6.x integration uses string
primary keys, which matches the default key type used by ASP.NET Identity.
警告
Unlike Entity Framework Core, Entity Framework 6.x doesn't support closed generic types, which prevents using the OpenIddict entities without subclassing them. As such, using a custom primary key type is a bit more complicated with Entity Framework 6.x than with Entity Framework Core and requires implementing custom entities, as highlighted in the next section.
Use custom entities
For applications that require storing additional data alongside the properties used by OpenIddict, custom entities can be used. For that, you need to:
Create custom entities:
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<TApplication, TAuthorization, TScope, TToken, TKey>()
方法强制 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>(); } }