Saturday, September 29, 2018

Set up a DbContext for the Entity Framework's Code First stuff.

Keeping with the Foo and the Bar object here I think we could have:

using Microsoft.EntityFrameworkCore;
using OurStuff.Data.Models;
namespace OurStuff.Data
{
   public class OurDbContext : DbContext
   {
      public DbSet<Foo> Foos { get; set; }
      public DbSet<Bar> Bars { get; set; }
      
      public OurDbContext(DbContextOptions options) : base(options)
      {
         
      }
      
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
         base.OnModelCreating(modelBuilder);
         
         modelBuilder.Entity<Foo>().ToTable("Foos");
         modelBuilder.Entity<Foo>().Property(f => f.FooId).ValueGeneratedOnAdd();
         modelBuilder.Entity<Foo>().HasMany(b => b.Bars).WithOne(f => f.Foo);
         
         modelBuilder.Entity<Bar>().ToTable("Bars");
         modelBuilder.Entity<Bar>().Property(b => b.BarId).ValueGeneratedOnAdd();
         modelBuilder.Entity<Bar>().HasOne(f => f.Foo).WithMany(b => b.Bars);
      }
   }
}

 
 

This comes from pages 173 and 174 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis. Do note the pluralized names for would be database tables. This has forever been the EF way while NHibernate geeks would just have a Foo table for the Foo object.

No comments:

Post a Comment