是否有必要直接使用上下文来进行工作?例如,我有一个客户数据库,用户可以通过姓名搜索客户,显示列表,选择一个客户,然后编辑该客户的属性。
似乎我应该使用上下文来获取客户列表(映射到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管理客户页面的用户界面将在客户沟通方式(打印、电子邮件、传真)下方包含三个复选框。我不能将每个复选框绑定到该枚举,这没有意义。而且,如果用户单击了该客户,然后起身去吃午饭……上下文会停留数小时,这很糟糕。相反,这是我的思考过程。
最终用户从列表中选择一个客户。我新建一个上下文,找到该客户并返回一个CustomerViewModel,然后关闭上下文(为简单起见,我在这里省略了存储库)。
using(MyContext ctx = new MyContext())
{
CurrentCustomerVM = new CustomerViewModel(ctx.Customers.Find(customerId));
}
现在用户可以勾选/取消勾选打印、电子邮件、传真按钮,因为它们绑定到CustomerViewModel中的三个bool属性,该属性还具有Save()方法。就是这样。
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();
}
}
}
你看到这个有什么问题吗?