Executing Raw Sql using Entity Framework

Posted by Sheonarayan under LINQ category on | Points: 40 | Views : 865
Sometimes, you might need to execute a particular SQL Statement through Entity Framework context. To do that, follow below approach.

            private TrainingMVCContext db = new TrainingMVCContext(); // EF context objecct
SqlParameter[] prms = new SqlParameter[3];
prms[0] = new SqlParameter("@FirstName", SqlDbType.VarChar, 50);
prms[0].Value = "Hari";
prms[1] = new SqlParameter("@LastName", SqlDbType.VarChar, 50);
prms[1].Value = "Shankar";
prms[2] = new SqlParameter("@AutoId", SqlDbType.Int);
prms[2].Value = 1050;

var sql = "UPDATE PersonalDetails SET FirstName = @FirstName, LastName = @LastName WHERE AutoId = @AutoId";

db.Database.ExecuteSqlCommand(sql, prms);

In the above code snippet, we have used the ExecuteSqlCommand method of the context.Database object and passed required parameter as SqlParameter array.

Hope this will help.


Comments or Responses

Login to post response