Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a SQL update query with a where clause using Entity Framework .NET Core

I only want to update a field based on the condition that is mentionned below. I know how to write it in SQL. I'm not sure how to accomplish this in entity framework.

UPDATE Table SET SomeDateTime = @NewDateTime WHERE Id = @MyId AND SomeDateTime > @NewDateTime

I want to use this particular query due to using a micro service architecture.

like image 215
Kevin Avatar asked Oct 16 '22 14:10

Kevin


1 Answers

If you want use sql directly you can use ExecuteSqlCommand

If you were handling a object and then doing a update I would change a object and call SaveChanges, but that's not the case.. here is an update directly to the table, If that table has millions of rows you want perform sql to get performance on that.

example

using(var context = new SampleContext())
{
    var commandText = "UPDATE Table SET SomeDateTime = @NewDateTime WHERE Id = @MyId AND SomeDateTime > @NewDateTime";
    var newDateTime = new SqlParameter("@NewDateTime", myDateValue);
    var myId = new SqlParameter("@MyId", myIdValue);

    context.Database.ExecuteSqlCommand(commandText,  new[]{newDateTime,myId});
}
like image 155
Alexandre Rodrigues Avatar answered Oct 19 '22 00:10

Alexandre Rodrigues