首页 文章

ASP.NET-Identity框架之外的实体无法正常工作

提问于
浏览
0

我正在玩ASP.NET 5身份并陷入困境 .

这是由Identity创建的样板上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Transaction> Transactions { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

我添加了一个存在于Identity框架之外的其他实体 Transactions .

当我启动网站时,所有身份验证的东西都工作正常,但当我尝试查询 Transactions 时,我收到此错误:

InvalidOperationException:未配置任何数据库提供程序 . 在设置服务时,通过在DbContext类或AddDbContext方法中覆盖OnConfiguring来配置数据库提供程序 .

进一步查看此错误,所有迹象似乎都指向在Startup.cs中注册服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddMvc();
}

尽管如此,仍然得到错误 .

谢谢!

1 回答

  • 0

    我知道这是愚蠢的,找到答案 .

    使用ef上下文时,在新派生时,不设置上下文 .

    所以需要注入:

    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _appCtx;
    
        public HomeController(
            ApplicationDbContext appCtx)
        {
            _appCtx = appCtx;
        }
    
        public JsonResult Durr()
        {
            return new JsonResult(_appCtx.Users.ToList());    
        }
    }
    

相关问题