【问题标题】:Getting IdentityFramework, IDesignTimeDbContextFactory, .NetCore 2.1, and DbContext to play nice together让 Identity Framework、IDesignTimeDbContextFactory、.Net Core 2.1 和 DbContext 协同工作
【发布时间】:2018-09-25 21:11:45
【问题描述】:

我有一个现有的 .Net 核心项目,我将 DBContext 分解到它自己的库中。在这个项目中,我使用 IDesignTimeDbContextFactory 为类库创建 DbContext。这让我可以使用 add-migration 和 update-database 之类的命令,尽管没有实际的 appsettings.json 或 app.config 文件可以从中提取连接字符串。

我现在的问题是我想做同样的事情,只是这次添加了 IdentityFramework。从我可以在线阅读的内容来看,执行此操作的标准方法似乎是放弃普通的旧 DbContext,并使所有内容都从 IdentityDbContext 继承。在我尝试添加 IDesignTimeDbContextFactory 之前,这似乎没问题。 IDesignTimeDbContextFactory 需要 DBContext 并且不能使用 IdentityDbContext。

我怎样才能拥有一个支持 IdentityFramework 和 IDesignTimeDbContextFactory 的类库?谁有例子?

我的项目结构是: .Web .API .Models(包含身份模型)

public class AppUser : IdentityUser
{
    public string MyExtraProperty { get; set; }
}


public class AppRole : IdentityRole
{
    public AppRole() : base() { }
    public AppRole(string name) : base(name) { }
}

.Service(包含 DbContext 和身份框架)

ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<AppUser>
{
     public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
     {
     }

     public static ApplicationDbContext Create()
     {
            return new ApplicationDbContext();
     }
 }

DBContextFactory (不喜欢ApplicationDbContext)

public class DBContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        builder.UseSqlServer(
            @"Server=(localdb)\MSSQLLocalDB;Database=IdentityFrameWork;AttachDBFilename=IdentityFramework.mdf;Trusted_Connection=True;MultipleActiveResultSets=true;");

    }
}

我需要一个单独的 .Net Standard 类中的 .Net Core 和 Identity 框架的工作示例。谁能帮帮我?

Git Hub Link

【问题讨论】:

  • 错误是什么?
  • 错误是:'IdentityFramework.Service.ApplicationDbContext'类型必须可转换为'Microsoft.EntityFrameworkCore.DbContext'

标签: c# entity-framework .net-core


【解决方案1】:

Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext 继承自 Microsoft.EntityFrameworkCore.DbContext,如您所见 here,这让我想知道您是否可能使用先前版本的 Identity Framework 和 AspNet.Identity.EntityFramework6.IdentityDbContext

【讨论】:

  • 我使用的是 .Net Core 2.1.3。 IDesignTimeDbContextFactory 也继承自 DbContext。我需要的是一个可以从 IdentityDbContext 继承的 IDesignTimeDbContextFactory 版本——这显然不存在。我想我需要考虑另一种方法来解决这个问题。
  • IDesignTimeDbContextFactory 不继承自 DbContext,它采用必须继承自 Microsoft.EntityFrameworkCore.DbContext 的类型参数。错误消息告诉您的是您的ApplicationDbContext 不继承自Microsoft.EntityFrameworkCore.DbContext,这就是为什么我建议您使用非.net 核心版本的身份框架。右键单击IdentityDbContext,转到定义,然后查看命名空间。是Microsoft.AspNetCore.Identity.EntityFrameworkCore吗?
  • 好吧,就是这样,现在我觉得自己很愚蠢。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 2016-06-25
相关资源
最近更新 更多