我正在尝试使用WCF数据服务和实体框架设计一种更好的SQL Server数据库更新方法。我遇到的问题是,使用该服务执行更新,删除和插入操作似乎过于复杂。
我将使用典型的客户/发票方案来帮助解释我当前的方法。我正在使用WPF MVVM作为应用程序。我的视图模型包含一个从用户接收更新的客户对象。保存时,我将客户对象传递给服务。然后,服务必须加载客户对象,从更新的客户传输属性值,然后执行保存。
这样的事情:
public static int SaveProgram(Customer entity)
int returnValue = 0;
// Setup the service Uri
Uri serviceUri = new Uri(Properties.Settings.Default.DataUri);
try
{
// Get the DB context
var context = new DevEntities(serviceUri);
Customer dbCustomer;
if (entity.CustomerId == 0)
{
dbCustomer = new Customer();
context.AddToCustomers(dbCustomer);
}
else
{
dbCustomer = context.Customers.Where(p => p.CustomerId == entity.CustomerId).FirstOrDefault();
}
if (dbCustomer != null)
{
dbCustomer.StatusId = entity.StatusId;
dbCustomer.FirstName = entity.FirstName;
dbCustomer.LastName = entity.LastName;
dbCustomer.Address = entity.Address;
...
}
context.UpdateObject(dbCustomer);
// Submit Changes
DataServiceResponse response = context.SaveChanges(SaveChangesOptions.Batch);
// Check for errors
...
returnValue = response.Count();
}
... Catch exceptions
return returnValue;
}
是否真的有必要通过所有这些?似乎应该有一种更简单的方法。
添加发票需要以下内容:
var newInvoice = Invoice.CreateInvoice(0, customerId, etc...);
context.AddRelatedObject(dbCustomer, "Invoices", newInvoice);
已经向Customer.Invoices集合添加了新发票,这看起来很麻烦。
删除发票更糟糕。要删除发票,我必须将数据库中的发票集合与传入的实体的发票集合进行比较。如果我在entity.Invoices集合中找不到发票的数据库版本,那么我知道它应该被删除。
我觉得我一定不能正确接近这个。