tags:

views:

618

answers:

6
+6  Q: 

Update in Linq

How can i update an entity that is disconnected from database?

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);
}
+1  A: 

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();
Adam Lassek
A: 

No, i want to update the given entity, id of which is 1. :/

yapiskan
can't understand in which case this answer deserve a down vote.
yapiskan
+1  A: 

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.

Adam Lassek
A: 

i know that but should i need to execute a select before update? there isn't a way to update without a select query?

yapiskan
+3  A: 

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();
Scott Nichols
A: 

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.

liammclennan
I disagree with the statement that this behavior is typical. It's certainly not the case with any ORM that implements the ActiveRecord pattern. In the opinion of many, this is a limitation of Linq To SQL. Some good discussion here: http://www.west-wind.com/Weblog/posts/135659.aspx
tlianza
Linq-to-sql does not implement Active Record.
liammclennan