直接使用上下文是否是個好主意?例如,假設我有一個客戶數據庫,用戶可以按名稱搜索它們,顯示一個列表,選擇一個,然後編輯該客戶的屬性。實體框架和WPF最佳實踐
看來我應該使用上下文來獲取客戶列表(映射到POCO或CustomerViewModels
),然後立即關閉上下文。然後,當用戶選擇列表中的CustomerViewModels
中的一個時,UI的客戶屬性部分填充。
接下來他們可以更改名稱,類型,網站地址,公司大小等。點擊保存按鈕後,我打開一個新的上下文,使用CustomerViewModel
中的ID檢索該客戶記錄,並更新其屬性。最後,我打電話SaveChanges()
並關閉上下文。這是很多工作。
我的問題是爲什麼不直接與整個環境打交道?我已閱讀使用相同的長壽命範圍的背景是非常糟糕的,並且不可避免地會導致問題。我的假設是,如果應用程序只能由一個人使用,我可以保持上下文暢通無阻。但是,如果將有許多用戶,我希望保持一個簡潔的工作單位,從而根據請求打開和關閉上下文。
有什麼建議嗎?謝謝。
@PGallagher - 感謝您的完整的答案。
@Brice - 您的輸入也很有幫助
但是,@Manos D.'冗餘代碼的縮影'評論讓我有點擔心。讓我通過一個例子。假設我將客戶存儲在數據庫中,並且我的一個客戶屬性是CommunicationMethod。
[Flags]
public enum CommunicationMethod
{
None = 0,
Print = 1,
Email = 2,
Fax = 4
}
我在WPF管理客戶頁面的UI將包含客戶通信方法(打印,電子郵件,傳真)下的三個複選框。我無法將每個複選框綁定到該枚舉,這是沒有意義的。此外,如果用戶點擊該客戶,起牀並去吃午餐......情景會在那裏呆上幾個小時,這很糟糕。相反,這是我的思維過程。
最終用戶從列表中選擇一個客戶。我新建一個上下文,找到這個客戶並返回一個CustomerViewModel,然後關閉這個上下文(爲了簡單起見,我已經把這個存儲庫留下了)。
using(MyContext ctx = new MyContext())
{
CurrentCustomerVM = new CustomerViewModel(ctx.Customers.Find(customerId));
}
此時用戶可以選擇/不選擇打印,電子郵件,傳真按鈕,因爲它們綁定到CustomerViewModel,其中也有一個Save()方法3個布爾屬性。開始。
public class CustomerViewModel : ViewModelBase
{
Customer _customer;
public CustomerViewModel(Customer customer)
{
_customer = customer;
}
public bool CommunicateViaEmail
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Email)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Email;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Email;
}
}
public bool CommunicateViaFax
{
get { return _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax); }
set
{
if (value == _customer.CommunicationMethod.HasFlag(CommunicationMethod.Fax)) return;
if (value)
_customer.CommunicationMethod |= CommunicationMethod.Fax;
else
_customer.CommunicationMethod &= ~CommunicationMethod.Fax;
}
}
public bool CommunicateViaPrint
{
get { return _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print); }
set
{
if (value == _customer.CommunicateViaPrint.HasFlag(CommunicationMethod.Print)) return;
if (value)
_customer.CommunicateViaPrint |= CommunicationMethod.Print;
else
_customer.CommunicateViaPrint &= ~CommunicationMethod.Print;
}
}
public void Save()
{
using (MyContext ctx = new MyContext())
{
var toUpdate = ctx.Customers.Find(_customer.Id);
toUpdate.CommunicateViaEmail = _customer.CommunicateViaEmail;
toUpdate.CommunicateViaFax = _customer.CommunicateViaFax;
toUpdate.CommunicateViaPrint = _customer.CommunicateViaPrint;
ctx.SaveChanges();
}
}
}
你看到有什麼問題嗎?
很好的答案。感謝您的回覆:英孚團隊成員的答案在這裏總是很有價值。 – JYL 2014-03-05 15:20:01