I typically use the Fluent API to configure my Entity Framework (Core) model. I think it gives me the most control without polluting my domain model with EF Core specific attributes.
You can do this directly inside the OnModelCreating method inside your DbContext but this can get out-of-control quite fast if you have a lot of objects to be mapped.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyContext : DbContext | |
{ | |
public DbSet<Blog> Blogs { get; set; } | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
modelBuilder.Entity<Blog>() | |
.Property(b => b.Url) | |
.IsRequired(); | |
} | |
} |
A better alternative is to use the IEntityTypeConfiguration<> interface together with the ApplyConfiguration method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BlogConfiguration : IEntityTypeConfiguration<Blog> | |
{ | |
public void Configure(EntityTypeBuilder<Blog> builder) | |
{ | |
builder.Entity<Blog>() | |
.Property(b => b.Url) | |
.IsRequired(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyContext : DbContext | |
{ | |
public DbSet<Blog> Blogs { get; set; } | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
modelBuilder.ApplyConfiguration(new BlogConfiguration()); | |
} | |
} |