Question

Code below does not run correctly and throws InvalidOperationExcepiton.

public void Foo()
{
 DataContext context = new DataContext();
 LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
 context.LinqEntities.Attach(item, true);
}
Was it helpful?

Solution

By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.

This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.

Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.

LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; 
context.LinqEntities.Attach(item);
item.Name = "John";
item.Surname = "Doe";
context.SubmitChanges();

OTHER TIPS

I'm not sure what you mean by disconnected from the database.

It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?

If that is the case you'll want to do

context.LinqEntities.InsertOnSubmit(item);
context.Submit();

OK, if you're trying to update a row with ID = 1, you'll do it like this:

DataContext context = new DataContext();
LinqEntity item = (from le in context.LinqEntities
                  where le.ID == 1
                  select le).Single();
item.Name = "John";
item.Surname = "Doe";

context.Submit();

You could also replace the Linq expression with a more concise lambda:

LinqEntity item = context.LinqEntities.Single(le => le.ID == 1);

The most important thing the DataContext does is track any changes you make, so that when you call the Submit method it will autogenerate the Insert statements for the things you've changed.

When using an ORM you typically select an object before updating it.

You can use DataContext.ExecuteCommand(...) to bypass the ORM if you do not want to do a select.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top