EntityFrameWork注意事項筆記
今天在開發時,偶然發現一個問題,而且是很容易粗心被忽略的ISSUE,假設我們有一個Table
名稱為:TestTable
裡面的資料表只有一行:
Message1 nvarchar(10)
我們用mvc來寫一下Code,其中Model如下
public class TestRepository
{
static dycoEntities _entity;
public dycoEntities entity
{
get
{
if (_entity == null)
_entity = new dycoEntities();
return _entity;
}
}
public void Create(TestTable data)
{
entity.AddToTestTable(data);
entity.SaveChanges();
}
}
Control如下
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(TestTable data)
{
try
{
TestRepository rp = new TestRepository();
rp.Create(data);
ModelState.AddModelError("validation-summary-valid", "成功");
}
catch
{
ModelState.AddModelError("validation-summary-valid", "錯誤");
return View(data);
}
return View(data);
}
考考各位,有沒有發現那裡有問題 ^_^
========================================================無聊的分格線=======================================================
======================================================無聊的空白========================================================
公怖答案,那就是Entity不能用static定義,會有問題
假設今天我們在畫面故意將Message1的欄位輸入超過20個字元時
想當然,系統會出現錯誤
接下來,我將20個字元改為5個字元,那應該沒問題了吧~~~
噹噹,還是錯誤,但Trace後,傳入的資料明明就是5個沒錯呀!!!
這時把static拿掉,一切就都正常囉 ^_^
至於為什麼會這樣,如果有先進知道原因,可以告知小弟 ^ ^; 感蝦