我遇到了一个奇怪的问题,我无法从数据库中获取对象然后重新附加它。我已经为其他项目编写了这样的代码,但由于一些奇怪的原因,它会在此应用程序中引发以下错误:
System.InvalidOperationException:只有在属性的当前值为null时才能设置EntityKey属性。
这是我的代码:
Entities.Customer customer;
using (var context = new XXEntities())
{
IQueryable<Entities.Customer> query = from a in context.Customers select a;
query = query.Where(c => c.CODE == "003046");
customer = query.ToList()[0];
}
using (var context = new XXEntities())
{
context.Customers.AddObject(customer);
context.SaveChanges();
}
答案 0 :(得分:0)
在第二个区块,
using (var context = new XXEntities())
{
//context.Customers.AddObject(customer);
context.Customers.Attach(customer);
context.SaveChanges();
}
EntitySet.Add()
表示添加新对象。您想要添加现有对象。