Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Last active January 4, 2019 09:46
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/5137c1c7eedecf3e8cd18f2f643f30cb to your computer and use it in GitHub Desktop.
Save christiannagel/5137c1c7eedecf3e8cd18f2f643f30cb to your computer and use it in GitHub Desktop.
BooksContext to use lazy loading with EF Core
public class BooksContext : DbContext
{
public BooksContext(DbContextOptions<BooksContext> options)
: base(options) { }
public DbSet<Book> Books { get; private set; }
public DbSet<Chapter> Chapters { get; private set; }
public DbSet<User> Users { get; private set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasMany(b => b.Chapters)
.WithOne(c => c.Book)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Book>()
.HasOne(b => b.Author)
.WithMany(a => a.WrittenBooks)
.HasForeignKey(a => a.AuthorId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Book>()
.HasOne(b => b.Reviewer)
.WithMany(r => r.ReviewedBooks)
.HasForeignKey(b => b.ReviewerId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Book>()
.HasOne(b => b.Editor)
.WithMany(e => e.EditedBooks)
.HasForeignKey(b => b.EditorId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Chapter>()
.HasOne(c => c.Book)
.WithMany(b => b.Chapters)
.HasForeignKey(c => c.BookId);
modelBuilder.Entity<User>()
.HasMany(a => a.WrittenBooks)
.WithOne(nameof(Book.Author))
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<User>()
.HasMany(r => r.ReviewedBooks)
.WithOne(nameof(Book.Reviewer))
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<User>()
.HasMany(e => e.EditedBooks)
.WithOne(nameof(Book.Editor))
.OnDelete(DeleteBehavior.Restrict);
SeedData(modelBuilder);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment