EF这个更新实体的时候

dbContext

           private TestProductContext db = new TestProductContext();

 

更新时候得需要去判断数据库纪录存不存在,那么

[HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                var model = (from p in db.Products where p.Id == product.Id select p).Count();

                if (model > 0)
                {                  
                    db.Entry(product).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
               
            }
            return View(product);
        }

 

如果需要model做别的事情呢()

 

 [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                var model = (from p in db.Products where p.Id == product.Id select p).FirstOrDefault();
                if (model != null)
                {                 
                    // 用model做点别的事情 (暂不考虑用model和提交product哪个更有意义)

        db.Entry(product).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            return View(product);
        }

 

So 程序出错了

[HttpPost]
public ActionResult Edit(Product product)
{
  if (ModelState.IsValid)
  {
    var model = (from p in db.Products where p.Id == product.Id select p).FirstOrDefault();
    if (model != null)
    {
      // 用model做点别的事情 (暂不考虑用model和提交product哪个更有意义)

      // db.Entry(product).State = EntityState.Modified;

      model.name1= product.name1;....

      model.name2= product.name2;....

      model.name3= product.name3;....


      db.SaveChanges();
      return RedirectToAction("Index");
    }
  }
  return View(product);
}

 

这样程序就可以了,不过。。。。。

      model.name1= product.name1;....

      model.name2= product.name2;....

      model.name3= product.name3;....

 

可以用组件EmitMapper

  EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>().Map(model, product);

 

用product代替model做别的事情好像更适合所有的场景   ? 

 

posted @ 2012-09-06 09:15  rayray2  阅读(361)  评论(0编辑  收藏  举报