Execute Parameterized Queries with “FromSqlRaw” method

The following code shows how to execute Parameterized Query with FromSqlRaw method. It will give all the students that have a name as Tony.

var context = new SchoolContext();
string name = "Tony";
var students1 = context.Student.FromSqlRaw($"Select * from Student where Name = '{name}'").ToList();

Using LINQ Operators with “FromSqlRaw” method

You can also use LINQ Operators after the result from FromSqlRaw() method.

The below code contains the .OrderBy() LINQ Operator that gives the result in ascending order of Student’s name.

var context = new SchoolContext();
var students = context.Student.FromSqlRaw("Select * from Student").OrderBy(x => x.Name).ToList();

Including related data

The Include method can be used to include related data.

var stuTeacher = context.Student
                        .FromSqlRaw($"SELECT * FROM Student")
                        .Include(b => b.Teacher)
                        .ToList();

Comments

Leave a Comment

All fields are required. Your email address will not be published.