標籤:style blog color os io 使用 ar for 檔案
VS2013上使用EF Power Tools的Reverse Engineer Code First逆向產生。
探索資料庫中的decimal(18, 4)欄位在產生的mapping類中沒有精度和小數位元。
這使得通過EF儲存資料時,自動產生的SQL預設使用了decimal(18, 2).
還好EF Power Tools提供了Customize Reverse Engineer Templates ,並給出了它使用的tt檔案。
開啟它的Mapping.tt
看到
if (type.ClrEquivalentType == typeof(int) || type.ClrEquivalentType == typeof(decimal) || type.ClrEquivalentType == typeof(short) || type.ClrEquivalentType == typeof(long)) { if (isKey && storeGeneratedPattern != StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)"); } else if ((!isKey || efHost.EntityType.KeyMembers.Count > 1) && storeGeneratedPattern == StoreGeneratedPattern.Identity) { configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)"); } }
果然對decimal沒處理精度。
加上以下代碼:
if(type.ClrEquivalentType == typeof(decimal)) { //foreach (var f in prop.TypeUsage.Facets) //{ // var scale = (Facet)f; // WriteLine("//Name:" + scale.Name ); //} var scale = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "Scale"); var precision = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "Precision"); configLines.Add(string.Format(".HasPrecision({0},{1})",precision.Value, scale.Value)); }
再次使用Reverse Engineer Code First。
得到帶精度的mapping。
this.Property(t => t.d0) .HasPrecision(18,0); this.Property(t => t.d2) .HasPrecision(18,2); this.Property(t => t.d4) .HasPrecision(18,4);
EF Power Tools 資料庫逆向產生時T4模板修改