日期:2014-05-18  浏览次数:20727 次

关于Entity FrameWork,有问题,来讨论下。
这是今天做的一个测试。
  private static void updateCust(Customers c)
  {
  NorthwindEntities n = new NorthwindEntities();
  c.CompanyName = "lulalua";
  n.SaveChanges();
  }

  然后我执行下面的代码:
  Customers customer = (from c in ne.Customers where c.CustomerID == "DFEGI" select c).FirstOrDefault();

  updateCust(customer);


  没有报错,跟踪updateCust里面,CompanyName也修改了。但是问题是,数据库并没有被更新。
  当然,我觉得这是因为,和Hibernate一样,虽然俩Customer表面看起来一样,但其实他俩并不是一个东西。现在的问题是怎么解决他?有没有类似的Merge的方法?我对EF的对象状态还不是非常了解,那位可以详细的讲讲。我并不想只传ID当参数,
去Find或者重新查询。那位大大科普一下嗖?!

------解决方案--------------------
探讨

引用:

引用:

如果分层等超出了上下文的操作。
那么即便是修改、删除超作,也要先把对象找出来,再重新赋值修改/删除,然后再保存。

---可参考三楼写法.

对啊,现在的问题就是如何在一个方法里,找到对象。其实这个对象是存在的,只是EF不知道就是他。


privat……

------解决方案--------------------
Basically, you were trying to update a detached entity. Here's what happened: you first extracted a customer entity from a context, but later you attempted to change that customer and open another context that customer.

The problem is: the second context had no idea of your customer entity extracted from the first context. If this is the way you want, you need to attach that customer back to the second context, by using: context.Attach(customer), and then, you must modify the customer's state to Modified, by using state manager.