直接使用上下文是否是个好主意?例如,假设我有一个客户数据库,用户可以按名称搜索它们,显示一个列表,选择一个,然后编辑该客户的属性。实体框架和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