Mapping in entity framework core has a little bit different configuration in comparison to the previous version of entity framework. Let's create a mapping for the following class:
public class Sail { public int Id { get; set; } public int SailerId { get; set; } public decimal Amount { get; set; } }
You should implement an interface named IEntityTypeConfiguration<T> like below:
public class SailConfiguration : IEntityTypeConfiguration<Sail> { public void Configure(EntityTypeBuilder<Sail> builder) { builder.HasKey(c => c.Id); builder.Property(c => c.Amount); builder.Property(c => c.SailerId); } }
In entity framework core, we don't have ToTable(tableName,schemaName) extension method in configuration anymore! In order to set table name or schema name, you should call ToTable in Entity<> of ModelBuilder in OnModelCreating() of DbContext derived class:
public class MyDbContext : DbContext { public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Sail>().ToTable("Sail", "MySchema"); modelBuilder.ApplyConfiguration(new SailConfiguration()); } }
I personally would rather create my own extension method over ModelBuilder :
public static class SailConfiguration { public static ModelBuilder MapSail(this ModelBuilder modelBuilder) { var entity = modelBuilder.Entity<Sail>(); entity.ToTable("Saile", "MySchema"); entity.HasKey(c => c.Id); entity.Property(c => c.Amount); entity.Property(c => c.SailerId); return modelBuilder; } }
And then map it OnModelCreating():
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.MapSail(); }
Category: Software
Tags: Entity Framework