3

I am trying to add properties to my ApplicationUser class but running into issues updating the database after I add the properties. What am I doing wrong? All I am trying to do is store the result of a claim inside the User object so I can access it easier.

I am trying to update the database using: EntityFrameworkCore\Add-Migration -Name ApplicationDbContext

Any time I run a command I am running it inside the NuGet Package Manager. I have also tried running commands via command prompt inside my project folder (with no success and similar error output).

Version info:

  • Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. I prefaced my commands with EntityFrameworkCore\

  • dotnet --version 2.1.101

Error

GenericArguments[0], 'MyWebsite1.Data.Migrations.ApplicationDbContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.

My ApplicationUser class:

 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";
            }
        }
    }

Heres the Up method inside ApplicationDbContext : Migration:

   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);
    }
}

my .csproj file:

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

As I was following along here when I tried: dotnet ef migrations add superuser_test I got: dotnet : No executable found matching command "dotnet-ef" despite having DotNetCliToolReference in my .csproj and running: dotnet restore

My migrations: enter image description here

Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • What does your context look like? See [here](https://stackoverflow.com/questions/45782446/unable-to-create-migrations-after-upgrading-to-asp-net-core-2-0) – Steve Greene Apr 25 '18 at 20:31
  • @SteveGreene I added my context. Is this what you were referring to? – Rilcon42 Apr 25 '18 at 23:24
  • Could be some dependency issue. What EF version, etc. See Ivan's answer [here](https://stackoverflow.com/questions/36776252/ef7-migration-in-pluralsight-course) – Steve Greene Apr 26 '18 at 13:28
  • Added my EF version, any other info that would be helpful here? Im not familiar with migrations and the Entity Framework – Rilcon42 Apr 26 '18 at 13:45

1 Answers1

0

Your ApplicationDbContext should implment IDesignTimeDbContextFactory<ApplicationDbContext> interfase check Design-time DbContext Creation

ApplicationDbContext should look like

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);
    }   
}

Also to run dotnet ef your projectfile.csproj should have 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>

Then open cmd at your project path and run

dotnet restore
dotnet ef
ElasticCode
  • 7,311
  • 2
  • 34
  • 45