EntityFramework CodeFirst Mapping to have camel case in the database

后端 未结 1 548
星月不相逢
星月不相逢 2021-01-25 06:26

I\'ve just started a new company who are happy for me to use CodeFirst - but want the database fields camel cased.

I\'m currently writing a lot of this kind of stuff ...

相关标签:
1条回答
  • 2021-01-25 07:01

    You can use code first custom conventions If using Fluent Api, you could alternatively use reflection of each Type in your context. Loop on each POCO and and for each PROPERTY set the name changing char1 to lowercase.

    modelBuilder.Entity<EFTestPoco>().Property(p=>p.UoM1).HasColumnName("camelCase");
    

    EDIT: The Reflection challenge includes dynamic lambda... Until you asked I didnt realise that the loop required dynamic lambda.... Opened my mouth too wide :-)

    ... This is a cut and paste from pieces of code i use. ... I use the EASIER /System.Linq.Dynamic approach

    You can use the Expression Complication library System.Linq.Expressions or You can use the easier to use Dynamic Lambda library to build dymanic Linq statements.
    SO here is the sample code

      // inside your context on model creating
      //....   
     // repeat for each poco.  // or reflect on thr context if feeling lazy and intellectual
     var entity = new EntityTypeConfiguration<Poco>;
    // Get the properties of a poco
        foreach (var propInfo in typeof(T).GetProperties()) {
                SetCamelCase<T>(propInfo,entity);
            }
     modelBuilder.Configurations.Add(entity);
     ....
     } // end of ON model creating
    
    
    
    private static void SetCamelCase<TModelPoco>(PropertyInfo propertyInfo, 
                                 EntityTypeConfiguration<TModelPoco> entity) where TModelPoco : BaseObject {
    
            var camel = propertyInfo.Name.Substring(0, 1).ToLower() + propertyInfo.Name.Substring(1);
    
            switch (propertyInfo.UnderLyingType().Name) {
                case SystemDataTypeConstants.String :
                var propLambdaString = System.Linq.Dynamic.DynamicExpression.ParseLambda<TModelPoco, string >(propertyInfo.Name);
                entity.Property(propLambdaString).HasColumnName(camel);
                break;
                case SystemDataTypeConstants.Int32:
                var propLambdaInt =System.Linq.Dynamic.DynamicExpression.ParseLambda<TModelPoco, int >(propertyInfo.Name);
                entity.Property(propLambdaInt).HasColumnName(camel);
                    break;
               //  SystemDataTypeConstants. // and teh rest you may use...
            }
    
    
        }
        public static Type UnderLyingType(this PropertyInfo propertyInfo) {
            return Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
        }
    
    0 讨论(0)
提交回复
热议问题