asp.net-core - ASP.NET Core Web API 错误:模型 1[TContext] 违反了“TContext”类型的约束
问题描述
我在 Visual Studio 2017 中有一个解决方案,其中包含以下项目:
CredentialManager.API(ASP.NET Core 2.1 Web API 项目)
CredentialManager.Models(包含领域模型和数据上下文类的类库)
领域模型类编码如下:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CredentialManager.Models.Entities
{
public class Credential
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long CredentialId { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Application { get; set; }
}
}
数据上下文类如下:
using System;
using System.Collections.Generic;
using System.Text;
using CredentialManager.Models.Entities;
using Microsoft.EntityFrameworkCore;
namespace CredentialManager.Models.Context
{
public class CredentialManagerContext : DbContext
{
public CredentialManagerContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Credential> Credentials { get; set; }
}
}
appsettings.json 文件如下所示:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"i.": null,
"CredentialManagerDB": "server=.\\SQLEXPRESS;database=CredentialManagerDB;Trusted_Connection=true;"
},
"AllowedHosts": "*"
}
Startup.CS 文件如下所示:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<CredentialManagerContext>(o => o.UseSqlServer(Configuration["ConnectionStrings:CredentialManagerDB"]));
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
然后我构建解决方案并添加迁移。但是当我运行 update-database 时,出现以下错误:
GenericArguments[0], 'CredentialManager.Models.Migrations.CredentialManagerContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.
这里有人可以解释一下这个错误吗?如果我将类和数据上下文包含在与 API 项目相同的文件夹中,那么一切正常。但我希望这些类成为单独的类库项目的一部分。任何帮助将非常感激。
谢谢。
解决方案
更新上下文文件以具有以下内容:
public CredentialManagerContext(DbContextOptions<CredentialManagerContext> options)
: base(options)
{ }
如文档中所述:
这需要向您的 DbContext 类型添加一个构造函数参数,该类型接受:
DbContextOptions<TContext>
这应该可以解决您的问题。
推荐阅读
- realm - 同一个 ArrayObject 上的领域 java 嵌套查询
- html - 我如何正确地将我的 sqlite3 行发送到我的 HTML 正文?
- objective-c - ThoMoNetworking 库:出现错误 EXC_BAD_INSTRUCTION
- php - Yii2 请求没有重定向到 actionError
- api - 我如何从linkedin检索所有用户活动
- domain-driven-design - 领域驱动的设计理念和与 CQRS 的关系
- r - 如何解决条形图中的误差线问题?
- hyperledger-fabric - 如何在背书/提交交易之前执行账本验证
- clickhouse - ClickHouse 创建临时表
- python - 如何将预测添加到多项式回归