2015年1月19日 星期一

Entity Framework Code First建立Decimal,並設定大小

在Sql建立Decimal的時候,習慣性會設定大小,但是在使用Entity Framework Code First的時候卻發現2個問題:
1.沒辦法改變大小(預設是18,2),可能欄位太大或是小數位數不夠
2.沒辦法檢查傳入的資料有沒有在限制的範圍內,可能會發生輸入不符合規則

有人會使用float或double,然後配合[RangeAttribute]去限制大小,以及[RegularExpressionAttribute]來檢驗格式;這或許解決了資料驗證的問題,但是總不可能每個欄位都去下這些屬性,對資料庫欄位大小問題也一樣沒有解決。
首先先來解決資料庫decimal大小問題。
網路上找的最快的方式(Set decimal(16, 3) for a column in Code First Approach in EF4.3):
public class MyContext : DbContext
{
  public DbSet<myclass> MyClass;
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<myclass>().Property(x => x.Sum).HasPrecision(5, 1);
    modelBuilder.Entity<myclass>().Property(x => x.Price).HasPrecision(3, 1);
    base.OnModelCreating(modelBuilder);
  }
}
解決了資料庫大小問題


測試下去就會發現,輸入多少都可以過,只是到資料庫會被截掉,要再加個驗證讓ModelState.IsValid可以為我們擋掉。
先建立一個DecimalAttribute繼承ValidationAttribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DecimalAttribute : ValidationAttribute
{
  public int Precision = 18;
  public int Scale = 2;
  public DecimalAttribute(int Precision = 18, int Scale = 2)
  {
    this.Precision = Precision;
    this.Scale = Scale;
  }
  public override bool IsValid(object value)
  {
    if (value == null)
    {
      return true;
    }
    try
    {
      decimal valueAsDecimal = Convert.ToDecimal(value);
      SqlDecimal sqlDecimal = SqlDecimal.ConvertToPrecScale(new SqlDecimal(valueAsDecimal), Precision, Scale);
    }
    catch (Exception ex)
    {
      if (string.IsNullOrEmpty(base.ErrorMessage) == true)
      {
        base.ErrorMessage = ex.Message;
      }
      return false;
    }
    return true;
  }
}
傳入資料測試驗證機制正常運行

延伸閱讀:
Entity Framework Code First依屬性(Attribute)設定SQL欄位
Entity Framework Code First依屬性(Attribute)設定SQL欄位 (續)

2014年12月19日 星期五

升級 Microsoft Azure Storage 4.3.0 以節省輸出流量、加快速度

使用 Microsoft Azure Storage 來擷取 Azure Table 的資料,通常要考慮速度與流量的最佳化,但原本的版本是 Microsoft Azure Storage 2.0.6,是沒有支援 OData 的,且 SDK 又是以 URL 去和 Azure Table 要資料,且一次都會要所有欄位資料,且速度也很慢,更別說還要做一些資料處理了。

我舉我的 Log 為例:

Log 資料欄位約略有 10 欄。
TableQuery query = (new TableQuery());
var data = table.ExecuteQuery(query);

var _query = (
    from entity in data
    // where entity.ErrorMessage != ""
    where entity.Timestamp > DateTime.Now.AddDays(-1)

    // where entity.Location.EndsWith("PUT")
    orderby entity.Timestamp descending
    select entity
);
DateTime std = DateTime.Now;

var r = _query.ToList();

DateTime etd = DateTime.Now;
TimeSpan diffDT = etd.Subtract(std);
Console.WriteLine("DateTime Method : {0} ms", diffDT.TotalMilliseconds);

資料有 370 筆,執行時間 25275.3736 ms,約 25 秒。

使用 Fiddler 來看:


由於 Azure Table 資料輸出有限制筆數,所以才會要那麼多次,每一份資料都 760000 bytes 左右,0.76 MB 左右。

升級 Microsoft Azure Storage 4.3.0 後,將程式碼稍微改一下,抓出需要使用的欄位就好:
TableQuery query = (new TableQuery()).Select(new string[] { "partitionKey", "Timestamp" });

資料有 330 筆,執行時間 9779.4132 ms,約 9.7 秒。

使用 Fiddler 來看:

這樣一來,既省輸出流量,也縮短時間,所以還沒有升級不訪升級試看看。



2014年11月25日 星期二

ASP.NET MVC 解決加入「控制器」( Controller ) 消失的問題

前陣子將專案升級,在 NuGet 安裝 ASP.NET Web API 2.2 for OData v4.0 套件,產生許多 dll 版本錯誤之問題。

修正後,又發現在要加入「控制項」( Controller ) 時,找不到該選項,如下圖:


甚至連加入「區域」( Areas ) 也找不到。

後來找到 visual studio 2013 'add controller' missing 文章解說,照以下方法即可解決:

1.

卸載專案

2.

編輯專案檔

3.

尋找 ProjectTypeGuids 標籤 ( 請先備分 ),將內容改為
<ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

儲存

4.

重新載入專案,完成。