2013-05-15 58 views
1

我剛開始一家新公司,他很高興我使用CodeFirst,但希望數據庫字段是駱駝式的。EntityFramework CodeFirst映射在數據庫中有駱駝案例

我目前正在寫了很多這種東西的...

[Column("active")] 
    public bool Active { get; set; } 

    [Column("paymentType")] 
    public string PaymentType { get; set; } 

有什麼辦法,我可以只是將其全部設置爲駝峯數據庫,而不是裝飾我的所有屬性?

感謝

+0

駱駝情況下,你的POCO會員? –

回答

1

您可以使用code first custom conventions 如果使用流利的API,你可以選擇使用各類型的反射在你的環境。 在每個POCO和每個PROPERTY上循環設置名稱將char1更改爲小寫。

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

編輯:反思挑戰包括動態拉姆達... 直到你問我沒有意識到需要的循環動態拉姆達.... 張開嘴太寬:-)

...這是從我使用的代碼片段剪切和粘貼。 ......我用更簡單的方法/System.Linq.Dynamic

您可以使用表達式併發症庫System.Linq.Expressions 或者您可以使用更容易使用Dynamic Lambda library 打造dymanic Linq的語句。
所以這裏是示例代碼

// 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

我會很高興做你的第二個建議,但沒有「屬性」實體<> - 只有屬性與屬性選擇器。我如何實際遍歷屬性?謝謝 –

相關問題