Loop/reflect through all properties in all EF Models to set Column Type

前端 未结 2 1600
走了就别回头了
走了就别回头了 2020-11-27 07:32

My client has a standard of storing SQL Server decimals with a decimal(13,4) specification. As a result, in a very large and still-growing schema, I have nearly a hundred st

相关标签:
2条回答
  • 2020-11-27 08:13

    In EF Core v1.1.0 you can use something like this:

    foreach (var pb in modelBuilder.Model
        .GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))
        .Select(p => modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
    {
        pb.ForSqlServerHasColumnType("decimal(13,4)");
    }
    

    Update (EF Core 2.x): Starting from EF Core 2.0, the model is built separately for each database provider, so HasAbcXyz methods are replaced with common HasXyz. The updated code (which also skips the explicitly configured properties) looks like this:

    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
    {
        if (property.Relational().ColumnType == null)
            property.Relational().ColumnType = "decimal(13,4)";
    }
    

    Update (EF Core 3.x): With EF Core 3.0 metadata API changes (Relational() extensions removed, properties replaced with Get / Set method pair), the code is as follows:

    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
    {
        if (property.GetColumnType() == null)
            property.SetColumnType("decimal(13,4)");
    }
    
    0 讨论(0)
  • 2020-11-27 08:25

    New feature will be introduced in EF Core 5.0

    modelBuilder
        .Entity<Blog>()
        .Property(b => b.Numeric)
        .HasPrecision(16, 4);
    

    Reference : https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#preview-4

    0 讨论(0)
提交回复
热议问题