.net core 2.0 - 值不能为空。参数名称:key

时间:2018-05-08 13:34:05

标签: asp.net-core asp.net-core-2.0

添加迁移时,包管理器控制台中出现此错误

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

我正在尝试添加组织实体:

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

这是我的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);
    }
}

当我运行应用程序时,它工作正常,但是当我尝试添加迁移时,它告诉我参数名称 - 键不能为空。有人可以在这里点灯吗?感谢

这是我的启动代码

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

1 个答案:

答案 0 :(得分:0)

  1. dbContext不应该IdentityDbContext<AppUser>而不是IdentityUserContext<AppUser>吗?

  2. ApplicationDbContext的构造函数不应该使用DbContextOptions类型的ApplicationDbContext吗?

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }
    
  3. 您不需要virtual个关键字吗?

    public DbSet<Organization> Organizations { get; set; }
    
  4. 改用AddIdentity

    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();
    
  5. 我不知道你从哪里得到代码,但它有点混乱,难以阅读。