0

How to use native queries with DBContext ? If I run the code, this give me exception. Why and what to do to run native query when using DBContext ?

AcademyEntities context = new AcademyEntities();

            string nativeSQLQuery =
                "SELECT * " +
                "FROM dbo.Employees " +
                "WHERE FirstName='{0}'";

            string name = "Guy";

            var emp = context.Departments.SqlQuery(nativeSQLQuery, name);

            foreach (var item in emp)
            {

            }
TheChampp
  • 1,337
  • 5
  • 24
  • 41

2 Answers2

1

You're querying the Employees table, but trying to materialize Department objects.

Change your call to:

var emp = context.Employees.SqlQuery(nativeSQLQuery, name);

( and remove the quotes round the {0} )

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
  • It worked.Thank you.I have one more question. With EF5 "AcademyEntities" inherit DBContext. In previous versions in EF (4.0) "AcademyEntities" inherit ObjectContext. Why in EF5.0 "AcademyEntities" interit DBContext ? Is it better ? What is the difference ? – TheChampp Jan 21 '13 at 18:23
  • @user1749358 excellent :) `DbContext` was introduced in EF 4.1 - most people use it now. – Nick Butler Jan 21 '13 at 18:26
  • Is this a good practice to use native sql queries in this way ? – TheChampp Jan 21 '13 at 18:28
  • @user1749358 No, it's not really good practice. You should use LINQ-to-Entities and let EF generate the SQL for you. It's also easier! You can download some samples from [`here`](http://weblogs.aspnet05.orcsweb.com/bschooley/archive/2007/10/25/msdn-s-101-linq-samples.aspx). Also, try out [`LINQPad`](http://www.linqpad.net/) – Nick Butler Jan 21 '13 at 18:32
  • What if I have more parametres? – Birhan Nega Nov 16 '20 at 09:02
1

You are querying Employees, so you should use context.Employees:

var emp = context.Employees.SqlQuery(nativeSQLQuery, name);
phnkha
  • 7,782
  • 2
  • 24
  • 31