我用下面的模式的一个稍微复杂的变化:
protected ActionResult Update<T>(Expression<Func<T, bool>> predicate, Action<IDataContext, T> action, params string[] whitelist) where T : class
{
using (var context = ContextFactory.GetContext())
{
try
{
var model = context.GetTable<T>().Where(predicate).SingleOrDefault();
if (model == null) throw new ApplicationException("Item not found");
if (whitelist != null && whitelist.Length > 0)
{
TryUpdateModel(model, whitelist);
}
else
{
TryUpdateModel(model);
}
if (action != null) action(context, model);
context.SubmitChanges();
return Success();
}
catch (SqlException ex)
{
return HandleSqlException(ex);
}
catch (Exception ex)
{
return Failure();
}
}
}
这可以让你写一个基本的更新动作简单:
public ActionResult Update(int id)
{
return Update<Customer>(c => c.CustomerID == id);
}
这将使用不同的过载的上述代码,其中Action<,>
未传入,用于允许您注入自定义绑定代码(如果TryUpdateModel
不足)。例如:
public ActionResult Update(int id)
{
return Update<Customer>
(
c => c.CustomerID == id,
(context, c) =>
{
c.LastModified = DateTime.Now;
}
);
}
它不是为所有更新的情况下具有足够的灵活性,但可能足以满足最愚蠢的CRUD场景。您可以使用它来集中您的异常处理,日志记录和困难类型属性的映射(主要是布尔值,因为如果未选中复选框,而且还可以为空值类型,则不会在HTML中发布复选框)。