向User类添加属性违反了类型TContext的约束条件。

3
我正在尝试向我的ApplicationUser类添加属性,但在添加属性后更新数据库时遇到了问题。我做错了什么?我只是想在用户对象中存储声明的结果,以便更轻松地访问它。
我正在尝试使用以下命令来更新数据库:EntityFrameworkCore\Add-Migration -Name ApplicationDbContext
每次运行命令时,我都在NuGet包管理器中运行它。我还尝试通过命令提示符在项目文件夹中运行命令(但没有成功,并出现了类似的错误输出)。
版本信息:
- Entity Framework Core和Entity Framework 6都已安装。 Entity Framework Core工具正在运行。我在我的命令前加了EntityFrameworkCore\ - dotnet --version 2.1.101
错误:
'GenericArguments[0], 'MyWebsite1.Data.Migrations.ApplicationDbContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.'
我的ApplicationUser类:
 public class ApplicationUser : IdentityUser
    {
        public string LGID { get; } = "";
        public string CoIDs { get; } = "";
        public string LGIDSuperUserName { get; set; } = "unknown"; //recently added
        public bool IsSuperUser { get; set; } = false; //recently added

        public ApplicationUser() { }

        public ApplicationUser(ClaimsIdentity identity)
        {
            IEnumerable<Claim> claims = identity.Claims;
            foreach (Claim c in claims)
            {
                if (c.Type == "LGID")
                    LGID = c.Value;
                if (c.Type == "CoIDs")
                    CoIDs = c.Value;
                if (c.Type == "LGIDSuperUser")
                    LGIDSuperUserName = c.Value;
                if (c.Type == "IsSuperUser")
                    IsSuperUser = c.Value.ToLower()=="yes";
            }
        }
    }

这是位于ApplicationDbContext : Migration中的Up方法:
   protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropIndex(
            name: "UserNameIndex",
            table: "AspNetUsers");

        migrationBuilder.DropIndex(
            name: "IX_AspNetUserRoles_UserId",
            table: "AspNetUserRoles");

        migrationBuilder.DropIndex(
            name: "RoleNameIndex",
            table: "AspNetRoles");

        migrationBuilder.AddColumn<bool>(
            name: "IsSuperUser",
            table: "AspNetUsers",
            nullable: false,
            defaultValue: false);

        migrationBuilder.AddColumn<string>(
            name: "LGIDSuperUserName",
            table: "AspNetUsers",
            nullable: true);

        migrationBuilder.CreateIndex(
            name: "UserNameIndex",
            table: "AspNetUsers",
            column: "NormalizedUserName",
            unique: true,
            filter: "[NormalizedUserName] IS NOT NULL");

        migrationBuilder.CreateIndex(
            name: "RoleNameIndex",
            table: "AspNetRoles",
            column: "NormalizedName",
            unique: true,
            filter: "[NormalizedName] IS NOT NULL");

        migrationBuilder.AddForeignKey(
            name: "FK_AspNetUserTokens_AspNetUsers_UserId",
            table: "AspNetUserTokens",
            column: "UserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
    }

ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

我的.csproj文件:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <_SelectedScaffolderID>MvcControllerWithContextScaffolder</_SelectedScaffolderID>
    <_SelectedScaffolderCategoryPath>root/Common</_SelectedScaffolderCategoryPath>
    <WebStackScaffolding_ControllerDialogWidth>600</WebStackScaffolding_ControllerDialogWidth>
    <WebStackScaffolding_DbContextDialogWidth>600</WebStackScaffolding_DbContextDialogWidth>
    <WebStackScaffolding_ViewDialogWidth>600</WebStackScaffolding_ViewDialogWidth>
    <WebStackScaffolding_IsLayoutPageSelected>False</WebStackScaffolding_IsLayoutPageSelected>
    <WebStackScaffolding_IsPartialViewSelected>False</WebStackScaffolding_IsPartialViewSelected>
    <WebStackScaffolding_IsReferencingScriptLibrariesSelected>False</WebStackScaffolding_IsReferencingScriptLibrariesSelected>
    <ActiveDebugProfile>IIS Express</ActiveDebugProfile>
    <NameOfLastUsedPublishProfile>FolderProfile</NameOfLastUsedPublishProfile>
    <Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
    <Controller_SelectedScaffolderCategoryPath>root/Controller</Controller_SelectedScaffolderCategoryPath>
    <WebStackScaffolding_IsAsyncSelected>False</WebStackScaffolding_IsAsyncSelected>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
  </PropertyGroup>
<DotNetCliToolReference   
Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version=”1.0.0” />
</Project>

当我按照这里的步骤进行操作时,运行了dotnet ef migrations add superuser_test命令后,我得到了错误提示:dotnet : No executable found matching command "dotnet-ef"。尽管我的.csproj中包含了DotNetCliToolReference并已运行dotnet restore
我的迁移记录如下图所示: enter image description here

你的上下文是什么样子?请参见这里 - Steve Greene
@SteveGreene 我添加了我的上下文。这是你所指的吗? - Rilcon42
可能是某些依赖关系问题。EF 版本等方面,请参见 Ivan 在这里的回答。 - Steve Greene
添加了我的EF版本,这里还有其他有用的信息吗?我不熟悉迁移和Entity Framework。 - Rilcon42
1个回答

0

你的ApplicationDbContext应该实现IDesignTimeDbContextFactory<ApplicationDbContext>接口,请查看Design-time DbContext Creation

ApplicationDbContext应该长成这样:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDesignTimeDbContextFactory<ApplicationDbContext>
{

    public ApplicationDbContext() { }

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

    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS; Database=TestEfCore; Trusted_Connection=True;");

        return new ApplicationDbContext(optionsBuilder.Options);
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }   
}

同时,要运行dotnet ef,你的projectfile.csproj应该包含以下内容

<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0-preview1-final" />
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0-preview1-final" />
</ItemGroup>

然后在您的项目路径下打开cmd并运行

dotnet restore
dotnet ef

尝试过使用 EntityFrameworkCore\Add-Migration -Name test1,但是仍然得到了相同的错误 :( - Rilcon42
你是否已经在迁移文件夹中删除了旧的 ApplicationDbContext 类? - ElasticCode
我在帖子中添加了迁移文件夹的截图,我需要删除哪个文件? - Rilcon42
如果您的数据库中没有关键数据,请删除迁移文件夹下的所有文件,并删除存在的数据库。 - ElasticCode
我只需要索赔表和用户表。如果我删除迁移下的所有这些文件,它会影响它们吗? - Rilcon42
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接