使用ASP.NET MVC使用L2S更新对象

时间:2010-04-29 23:32:11

标签: asp.net-mvc linq-to-sql

是否有更简单的方法用L2S更新对象,然后按属性执行属性?

这就是我现在正在做的事情:

Public ActionResult Edit(Object obj)
{
    var objToUpdate = _repository.Single<Object>(o => o.id = obj.id);
    objToUpdate.Prop1 = obj.Prob1;
    objToUpdate.Prop2 = obj.Prop2;

    ...

    _repository.SubmitChanges();
}

我希望有一种方法可以说objToUpdate = obj然后提交更改???

对此有任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

我使用了以下模式的稍微复杂的变体:

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中发布复选框,但也可以为可空值类型)。

答案 1 :(得分:-1)

你做得对。您需要有一个DataContext来实际进行更新,MVC将无法为您创建。但是,您可以做很多事情来减少控制器中的代码,因此它看起来要简单得多。这就是我们在工作中所做的。我们有模板化的方法以更清洁的方式处理事情。

相关问题