Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use old style sql in mvc4

I am learning MVC4 and I got the idea of Entity Framework. But I wonder how you do the old style sql statements in MVC 4.

lets say I have this action with EF code

public ActionResult Index(){
    var model = from r in restaruants
                select r;
    return View(model);
}

Is it possible to do a old style sql instead of EF in the index function?

what I mean with old style sql is like "select * from restaurant"

public ActionResult Index(){
   /* Can I have something like this? */
   var model = Return_Model_Somehow("select * from restaurants");

   return View(model);
}
like image 605
Arif YILMAZ Avatar asked Jun 03 '13 13:06

Arif YILMAZ


2 Answers

You can execute raw sql with SqlQuery method:

var model = context.Database.SqlQuery<Restauraunt>("SELECT * FROM Restaruants")
                   .ToList();
return View(model);

Here is MSDN article: Raw SQL Queries.

like image 86
Sergey Berezovskiy Avatar answered Nov 19 '22 01:11

Sergey Berezovskiy


MVC (All versions) do not suppose/force any data access method, if you mean 'Linq' then:

string q = "SELECT *FROM Table1";
IEnumerable<Entities.Table1> res = context.ExecuteQuery<Entities.Table1>(q);

Now you have the result as an enumerable collection, use it as you want.

Hope that helps.

like image 29
Ken D Avatar answered Nov 19 '22 00:11

Ken D