Kind a simple problem, but i am completely lost on how to approach to this.
CREATE TABLE Contract (
id int PRIMARY KEY,
batchId int NOT NULL REFERENCES ContractBatch (id)
campaignId int NULL REFERENCES Campaign (id)
)
This is simplified table in my business model, made to Linq2Sql model. Now i need to do update query like this:
UPDATE Contract SET campaignId = 1 WHERE batchId = 5
That means, there can be more records for same ContractBatch and i need to set Campaign for all of them. Is it possible to convert this query to Linq expression in some easy way ? Only way i am able find is fetch all those records for that ContractBatch and then update one by one in loop. That’s not very efficient.
var campaignId = 1;
var batchId = 5;
using( var dataContext = new DataModel.ModelDataContext() ) {
dataContext.Contracts
.Where( c => c.BatchId == batchId )
// this is obviously my "wish to have" method
.ForEach( c => c.CampaignId = campaignId )
dataContext.SubmitChanges()
}
I am already thinking about doing it in old way and execute that query by hand. I don’t like it, but it’s probably better than running like hundreds of update queries.
You are right that there are two problems with this approach – you will be executing hundreds of individual update statements, and you have to read them in the first place to do the change.
This is a common weakness in ORMs.
Following a few google links I found the following blog post, which does have some interesting things to say in this area:
http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx