Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Last active Jan 4, 2019
Embed
What would you like to do?
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