tags:

views:

62

answers:

4

Hi

every example I seen shows how to do a update query in linq to sql by doing this.

// grab entity you want to update

entity.UserId = "123"; // update the fields you want to update.
entity.Name = "bob";

Dbcontext.SubmitChanges();

I am wondering can you juse pass in a new object and have it figure it out?

Like could I do this?

Enity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:

    // grab entity record
    // shove record ito the found record
    // it figured out what to update and what no to update
+2  A: 

Depending on what exactly you want to do you either need the InsertOnSubmit method, or the Attach method of the respective table (i.e. dbContext.Entities). InsertOnSubmit is used to add a record, while Attach can be used if you want to affect an UPDATE without having to first SELECT the record (you already know the primary key value)

David
I don't know much about linq to sql or this attach method. All I know is what I showed you above where you grab the record then do changes to it and submit.
chobo2
A: 

If you want to do this for performance reasons then you shouldn't worry about it. Linq to Sql will cache objects locally so that just grabbing an entity by ID to modify some fields is very cheap.

joshperry
nothing to do this with preformance issues(I would figure what I am trying to do would be even a bit slower) but I was thinking since with asp.net mvc you can have it as a method paramerter it kind of sucks that you got to then pass it in then go MyEntity.UserId = MyParamerterEntity.UserId; seems kinda redudent.
chobo2
A: 

It's possible to attach and persist it to the database, however you may want to set a field to check for concurrency (ie LastModified).

If you are going to use the Attach method on the data context, you need to set the primary/composite keys before you attach the entity (so you don't trigger INotifyPropertyChanging, INotifyPropertyChanged events).

Elijah Glover
A: 

In the case you have the dbContext available and ready, just add InsertOnSubmit:

Entity myEntity = new Entity();
myEntity.UserId = "123";
myEntity.Name = bob:

Dbcontext.InsertOnSubmit(myEntity);

Dbcontext.SubmitChanges();

As the name of the method implies, this will insert your new entity into the database on calling SubmitChanges.

Marc

marc_s