首页 > 解决方案 > 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 项目相同的文件夹中,那么一切正常。但我希望这些类成为单独的类库项目的一部分。任何帮助将非常感激。

谢谢。

标签: asp.net-coreasp.net-core-webapi

解决方案


更新上下文文件以具有以下内容:

public CredentialManagerContext(DbContextOptions<CredentialManagerContext> options)
     : base(options)
{ }

如文档中所述:

这需要向您的 DbContext 类型添加一个构造函数参数,该类型接受:

DbContextOptions<TContext>

这应该可以解决您的问题。


推荐阅读