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

时间:2018-04-24 15:57:06

标签: asp.net entity-framework identity ef-migrations

我正在尝试向ApplicationUser类添加属性,但在添加属性后遇到更新数据库的问题。我究竟做错了什么?我想要做的就是将声明的结果存储在User对象中,这样我就可以更轻松地访问它了。

我正在尝试使用:EntityFrameworkCore\Add-Migration -Name ApplicationDbContext

更新数据库

每次运行命令时,我都会在NuGet包管理器中运行它。我也尝试通过命令提示符在我的项目文件夹中运行命令(没有成功和类似的错误输出)。

版本信息:

  • 安装了Entity Framework Core和Entity Framework 6。实体框架核心工具正在运行。我用EntityFrameworkCore\

  • 开始了我的命令
  • dotnet --version 2.1.101

错误

  

GenericArguments [0],   'MyWebsite1.Data.Migrations.ApplicationDbContext',开启   'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1 [TContext]'   违反了'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中的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>

当我尝试跟随here时:dotnet ef migrations add superuser_test我得到了dotnet : No executable found matching command "dotnet-ef",尽管我的.csproj中有DotNetCliToolReference并且正在运行:dotnet restore

我的迁移: enter image description here

1 个答案:

答案 0 :(得分:0)

您的ApplicationDbContext应该IDesignTimeDbContextFactory<ApplicationDbContext> interfase check 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 应该有bwlow

<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>

然后open cmd at your project path并运行

dotnet restore
dotnet ef