Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The seed entity for entity type 'X' cannot be added because the was no value provided for the required property "..ID"

I'm playing wit EF Core 2.1 Preview 2. I have troubles with HasData (Seed) method in OnModelCreating(ModelBuilder modelBuilder)

My model is simple POCO class that has no annotation.

public class Tenant {
    public int TenantID {get; set;}
    public string Name {get; set;}
}

in my DbContext inside OnModelCreating method is DB model defined as

modelBuilder.Entity<Tenant>(e => {
    e.HasKey(m => m.TenantID)
     .HasName("PK_Tenants");

    e.Property(m => m.TenantID)
     .UseSqlServerIdentityColumn();

    e.Property(m => m.Name)
     .IsRequired()
     .HasMaxLength(256);
}

and the seed mehod is defined as:

modelBuilder.Entity<Tenant>().HasData(new []{
   new Tenant {
      TenantID = 0,
      Name = "SystemTenant",
   }
});

During startap, when ctx.Database.Migrate() is run, I got exception: The seed entity for entity type 'Tenant' cannot be added because there was no value provided for the required property 'TenantID

like image 350
Tomino Avatar asked Apr 24 '18 20:04

Tomino


1 Answers

The exception is little bit misleading. There must be some mechanism inside, that tests required properties so they must be different to a default values.

The only change I had to do was specifying TenantID != 0.

modelBuilder.Entity<Tenant>().HasData(new []{ 
   new Tenant {
      TenantID = 1, // Must be != 0
      Name = "SystemTenant",
   }
});
like image 137
Tomino Avatar answered Sep 19 '22 12:09

Tomino