【问题标题】:Value cannot be null. (Parameter 'key') in ASP.NET Core 3..0值不能为空。 ASP.NET Core 3..0 中的(参数“键”)
【发布时间】:2020-05-27 11:19:06
【问题描述】:

我需要在 ASP.NET Core 3.0 中使用代码优先创建数据库

这是DbContext

public class TrelloContext : DbContext
{
    public TrelloContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.AddDbSet<IEntity>(typeof(IEntity).Assembly);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(IType).Assembly);
    }
}

这是启动:

public void ConfigureServices(IServiceCollection services)
{
        services.AddControllers().AddControllersAsServices();
        services.AddDbContext<TrelloContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));
        services.Injection();
}

这是我的连接字符串:

"ConnectionStrings": {
    "SqlServer": "Data Source=.;Initial Catalog=TrelloDB;Trusted_Connection=True;Trusted_Connection=True;"
}

当我使用这个add-migration initial 时,我得到这个错误:

值不能为空。 (参数'key')

有什么问题?我该如何解决这个问题?

【问题讨论】:

  • 也可以添加堆栈跟踪。
  • 什么是`modelBuilder.AddDbSet(typeof(IEntity).Assembly);`?你用vs 2019 16.3吗?您是否尝试过重建解决方案?

标签: c# asp.net asp.net-core


【解决方案1】:

这是因为您的一个实体(继承自接口:IEntity)没有标识列。

请检查您的所有实体。确保他们都有一个 ID 或标记为 [Key] 的属性。

public class MyEntity : IEntity
{
    // make sure:
    public int Id { get; set; }
    // or:
    [Key]
    public int SomeProperty { get; set; }
}

【讨论】:

    【解决方案2】:

    仅用于注册,当从现有表创建 UniqueKey 时,DDD 中也会发生这种情况,并且 UniqueKey 字段之间已经存在重复记录。

    例子:

    //SQL: [dbo].[User]:
    Id | Name | Login
    1  | Thi  | thi.xpto
    2  | Thi  | thi.xpto
    
    
    [Table("User")]
    public class User
    {
      [Key]
      public int Id { get; set; }
      public string Name { get; set; }
      public string Login { get; set; }
    }
    
    public class UserDbContext : DbContext
    {
      ...
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
        modelBuilder.Entity<User>()
          .HasAlternateKey(x => new { x.Name, x.Login })
          .HasName("UK_User_NameLogin");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2014-05-17
      • 2018-02-11
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多