Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Created August 28, 2018 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannagel/add698a7bf60c25a86b258abce1eeb3f to your computer and use it in GitHub Desktop.
Save christiannagel/add698a7bf60c25a86b258abce1eeb3f to your computer and use it in GitHub Desktop.
Seeding data with EF Core 2.1
public class BooksContext : DbContext
{
private const string ConnectionString = @"server=(localdb)\MSSQLLocalDb;database=Books1;trusted_connection=true";
public DbSet<Book> Books { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(ConnectionString)
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Book>().Property(b => b.Title)
.IsRequired()
.HasMaxLength(50);
modelBuilder.Entity<Book>().Property(b => b.Publisher)
.IsRequired(false)
.HasMaxLength(30);
modelBuilder.Entity<Book>().HasData(
new Book { BookId = 1, Title = "Professional C# 6", Publisher = "Wrox Press"},
new Book { BookId = 2, Title = "Professional C# 7", Publisher = "Wrox Press"},
new Book { BookId = 3, Title = "Professional C# 8", Publisher = "Wrox Press"}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment