关于Entity FrameWork,有有关问题,来讨论下
关于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或者重新查询。那位大大科普一下嗖?!
------解决方案--------------------
------解决方案--------------------
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.
这是今天做的一个测试。
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或者重新查询。那位大大科普一下嗖?!
------解决方案--------------------
------解决方案--------------------
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.