mr-dortaj
mr-dortaj

Reputation: 852

Value cannot be null. (Parameter 'key') in ASP.NET Core 3..0

I need to create a database with code-first in ASP.NET Core 3.0

This is the 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);
    }
}

and this is startup :

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

This is my connection string :

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

When I use this add-migration initial, I get this error:

Value cannot be null. (Parameter 'key')

What's the problem? How can I solve this?

Upvotes: 3

Views: 16153

Answers (2)

for registration only, this also occurs in the DDD when a UniqueKey is created from an existing table, and duplicate records already exist between UniqueKey fields.

Example:

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

Upvotes: 1

Anduin Xue
Anduin Xue

Reputation: 3727

It was because of one of your entities (inherited from interface: IEntity) do not have an identity column.

Please check all your entites. Make sure they all have an ID or a property marked as [Key].

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

Upvotes: 5

Related Questions