demo
demo

Reputation: 6235

Update Collection of entities in IQueryable mode

I should rewrite SQL code in C# code using EF:

UPDATE Submissions SET Other_Platform = (SELECT top 1 Other_Platform FROM Submission_Platform_Other_DistributionMethods WHERE Submission_ID = @SubmissionId )   

Cause there are to many records in table Submissions i don't want to convert this collection into List to update field in loop.

Have anybody some ideas? Thanks.


var otherPlatform = db.Submission_Platform_Other_DistributionMethods.FirstOrDefault(d => d.Submission_ID == subId);
var toUpdate = db.Submissions.Select(s=> UpdateSubmission(otherPlatform));

db.Submissions.AddRange(toUpdate);
db.SaveChanges();

This is one possible solution that came to my head - create some method(like mapper) which takes parameter to set as Other_Platform

Upvotes: 0

Views: 996

Answers (1)

Janne Matikainen
Janne Matikainen

Reputation: 5121

If you want to keep the context alert of the updates you have done. Then I dont think there is any other way than to loop through the collection and update the platform and then saving the changes.

Two other ways you can do however these would mean the changes go past your entities that are loaded in the context and you would have to recreate the context(s).

1) create a stored procedure and execute that with the parameter you are providing

2) execute sqlcommand to the context

using (var context = new MyContext()) 
{ 
    context.Database.SqlCommand("<update query here>"); 
}

Upvotes: 1

Related Questions