Sto giocando con EF Core 2.1 Preview 2 . Ho problemi con il metodo HasData (Seed) in OnModelCreating(ModelBuilder modelBuilder)
Il mio modello è semplice classe POCO che non ha annotazioni.
public class Tenant {
public int TenantID {get; set;}
public string Name {get; set;}
}
nel mio DbContext
all'interno del metodo OnModelCreating
è definito il modello DB
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);
}
e il seed mehod è definito come:
modelBuilder.Entity<Tenant>().HasData(new []{
new Tenant {
TenantID = 0,
Name = "SystemTenant",
}
});
Durante lo startap, quando viene eseguito ctx.Database.Migrate (), ho ottenuto un'eccezione: l'entità seed per il tipo di entità 'Tenant' non può essere aggiunta perché non è stato fornito alcun valore per la proprietà richiesta 'TenantID
L'eccezione è un po 'fuorviante. All'interno deve esserci un meccanismo che collauda le proprietà richieste in modo che siano diverse da un valore predefinito.
L'unico cambiamento che dovevo fare era specificare TenantID != 0
.
modelBuilder.Entity<Tenant>().HasData(new []{
new Tenant {
TenantID = 1, // Must be != 0
Name = "SystemTenant",
}
});
Ho creato un piccolo "hack" per aggirare la restrizione del valore PK 0 dopo aver invertito il codice EF Core e ho trovato questa riga di codice. Relativo alla risposta @Tomino . Ecco il mio codice di estensione snipped:
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace EntityFrameworkCore.CustomMigration
{
public static class CustomModelBuilder
{
public static bool IsSignedInteger(this Type type)
=> type == typeof(int)
|| type == typeof(long)
|| type == typeof(short)
|| type == typeof(sbyte);
public static void Seed<T>(this ModelBuilder modelBuilder, IEnumerable<T> data) where T : class
{
var entnty = modelBuilder.Entity<T>();
var pk = entnty.Metadata
.GetProperties()
.FirstOrDefault(property =>
property.RequiresValueGenerator()
&& property.IsPrimaryKey()
&& property.ClrType.IsSignedInteger()
&& property.ClrType.IsDefaultValue(0)
);
if (pk != null)
{
entnty.Property(pk.Name).ValueGeneratedNever();
entnty.HasData(data);
entnty.Property(pk.Name).UseSqlServerIdentityColumn();
}
else
{
entnty.HasData(data);
}
}
}
}
E puoi usarlo in questo modo nel metodo OnModelCreating
:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Seed(new List<Tenant> {
new Tenant() {TenantID = 0 , Name = string.Empty},
new Tenant() {TenantID = 1 , Name = "test"}
//....
);
//....
}