4

I have such error in package manager console when Add-Migration

Entity Framework Core 2.0.1-rtm-125 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: MigrationsAssembly=Project.Data 
System.ArgumentNullException: Value cannot be null.
Parameter name: key
at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
   at Microsoft.EntityFrameworkCore.RelationalMetadataExtensions.Relational(IKey key)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.<Add>d__35.MoveNext()
   at System.Linq.Enumerable.<CastIterator>d__34`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.<Add>d__26.MoveNext()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.<DiffCollection>d__50`1.MoveNext()
   at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IModel source, IModel target)
   at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Value cannot be null.
Parameter name: key

I'm trying to add Organization entity:

public class Organization 
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
}

This is my AppDbContext

public class ApplicationDbContext : IdentityUserContext<AppUser>
{
    public virtual DbSet<Organization> Organizations { get; set; }

    public ApplicationDbContext(DbContextOptions options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

When I run application, it works fine, but when I'm trying to add migration it tells me that parameter name - key can't be null. Can someone please shed some lights here? Thanks

This is my Startup code

    public class Startup
{
    public IConfiguration _configuration { get; }

    // Inject project configuration
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // This method gets called by the runtime.
    // Use this method to add services to the conteiner.
    public void ConfigureServices(IServiceCollection services)
    {
        #region Database

        // Add Database Context
        services.AddDatabase(_configuration);

        #endregion

        ...

        #region Identity
        // Add Identity 
        // TODO: Extract to external extension method .AddIdentity()
        var builder = services.AddIdentityCore<AppUser>(o =>
        {
            // Configure Identity options
            o.Password.RequireDigit = false;
            o.Password.RequireLowercase = false;
            o.Password.RequireUppercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequiredLength = 6;
        });
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
        #endregion

        ...            

        services.AddAutoMapper();
        services.AddMvc();
    }

    // This method gets called by the runtime.
    // Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // TODO: Add development configuration
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        ...            

        // Configure application for usage as API
        // with default route of '/api/[Controller]'
        app.UseMvcWithDefaultRoute();

        // Configures application to serve the index.html file from /wwwroot
        // when you access the server from a browser
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
}
Dmytro
  • 16,668
  • 27
  • 80
  • 130
Sergiy Divnych
  • 149
  • 2
  • 13
  • Can you post your startup code? Have you got your connection strings correct? – Narwen May 08 '18 at 14:03
  • @Narwen Yes, my connection string is fine cause I have registered few users already – Sergiy Divnych May 08 '18 at 14:23
  • @Narwen `public static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration) { var connetctionString = configuration.GetConnectionString("AppConnection"); services.AddDbContext(options => options.UseSqlServer(connetctionString, b => b.MigrationsAssembly("Project.Data"))); return services; }` – Sergiy Divnych May 08 '18 at 14:23
  • @Narwen I have added my Startup code to my question – Sergiy Divnych May 08 '18 at 14:27
  • Just change the connection string and try fresh migration!! See if the issue is with the adding further migrations or migration itself! – Narwen May 08 '18 at 14:53
  • Check this one as well!! https://stackoverflow.com/questions/46010003/asp-net-core-2-0-value-cannot-be-null-parameter-name-connectionstring?rq=1 – Narwen May 08 '18 at 14:54
  • @Narwen I had tryed this solution [link](https://stackoverflow.com/questions/46010003/asp-net-core-2-0-value-cannot-be-null-parameter-name-connectionstring?rq=1) but issue is the same. Also I had change connection string and received same error – Sergiy Divnych May 08 '18 at 14:59
  • Sorry mate but I need to look at your project to get more insights in order to help. – Narwen May 08 '18 at 15:02

1 Answers1

1
  1. Shouldn't the dbContext be called IdentityDbContext<AppUser> not IdentityUserContext<AppUser>?

  2. Shouldn't the constructor of ApplicationDbContext take the DbContextOptions of the type ApplicationDbContext?

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }
    
  3. You don't need virtual keyword do you?

    public DbSet<Organization> Organizations { get; set; }
    
  4. Use AddIdentity instead?

    services.AddIdentity<AppUser, AppRole>(options =>
        options.User.RequireUniqueEmail = true/false;
    
        options.Password.RequireDigit = true/false;
        ...
    })
    .AddEntityFrameworkStores<ApplicationDbContext>()
    // Components that generate confirm email and reset password tokens.
    .AddDefaultTokenProviders();
    

I don't know where you got the code from but it's kind of messy and hard to read.

David Liang
  • 20,385
  • 6
  • 44
  • 70
  • 1
    Thanks for reply. I have changed my code as you wrote but issue is the same as it was. Maybe you have some other idea about this issue? – Sergiy Divnych May 10 '18 at 07:48
  • well I don't have the details on many pieces of your code. For example, `services.AddDatabase(_configuration)` looks like an extension method you wrote? And what's the `IdentityUserContext` class? That's hard to figure out the issue here with just little information. If you want, you can create a github repo and I can take a look from there. – David Liang May 10 '18 at 17:40