Last active
October 23, 2021 05:12
-
-
Save CarlosLanderas/393798c21297c3e210b593350cd2e339 to your computer and use it in GitHub Desktop.
EF Core Model Builder extensions to apply global conventions
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
using Microsoft.EntityFrameworkCore; | |
namespace Microsoft.EntityFramework.Conventions.Extensions | |
{ | |
public class Context : DbContext | |
{ | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
modelBuilder.SetGlobalMaxLength(200); | |
modelBuilder.SetGlobalTablePrefix("tbl_"); | |
base.OnModelCreating(modelBuilder); | |
} | |
} | |
} |
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
using System; | |
using System.Linq; | |
using Microsoft.EntityFrameworkCore; | |
namespace Microsoft.EntityFramework.Conventions.Extensions | |
{ | |
public static class ModelBuilderExtensions | |
{ | |
public static void SetGlobalMaxLength(this ModelBuilder modelBuilder, int maxLength) | |
{ | |
if (maxLength == default) | |
{ | |
throw new ArgumentNullException(nameof(maxLength)); | |
} | |
foreach (var entity in modelBuilder.Model.GetEntityTypes()) | |
{ | |
foreach (var property in entity.GetProperties().Where(p => p.ClrType == typeof(string))) | |
{ | |
property.SetMaxLength(maxLength); | |
} | |
} | |
} | |
public static void SetGlobalTablePrefix(this ModelBuilder modelBuilder, string prefix, bool useLowercase = true) | |
{ | |
foreach (var entity in modelBuilder.Model.GetEntityTypes()) | |
{ | |
var tableName = | |
useLowercase ? | |
$"{prefix}entity.ClrType.Name".ToLower() : | |
$"{prefix}entity.ClrType.Name"; | |
modelBuilder.Entity(entity.Name).ToTable(tableName); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment