Entity Framework Core 5 is an open-source, lightweight, extensible, and a cross-platform ORM. It is easy to apply and it makes database access super simple. However, sometimes working with tables and views is just not enough. How to execute raw SQL script with Entity Framework Core 5? Let’s find out.

Running the raw SQL

Running a SQL without carrying about the result is quite easy. Have a look at this example:

1

await primeDbContext . Database . ExecuteSqlInterpolatedAsync ( < br /> $ “UPDATE Profiles SET Country = ‘Poland’ WHERE LEFT(TelNo, 2) = ‘48’ AND Id > {minimalProfileId}” );

This SQL updates the Country based on TelNo column for profiles with Id higher then the one provided. It is just a few lines of code and it works perfectly! It also shows how we can pass a parameter to SQL, but you also can format it with curly braces.

Executing a stored procedure

A stored procedure is a perfect example of a SQL, that you might want to run directly on the database, but keep SQL on the database side. Let’s say you already have a stored procedure named UpdateProfilesCountry with one parameter. If you would just like to execute it, you could simply have a code like this:

1

2

await primeDbContext . Database . ExecuteSqlInterpolatedAsync (

$ “UpdateProfilesCountry {minimalProfileId}” );

You don’t need a DbSet to map the results, so you can use DbContext.Database.ExecuteSqlRawAsync and pass parameters if you’d like to.

If you’d like to get the full picture, read the separate article: Execute a stored procedure with Entity Framework Core 5.

#asp.net core for .net 5 & ef core 5 #ef core 5 #primehotel #sql

Executing raw SQL with Entity Framework Core 5
2.95 GEEK