How to write pure SQL in asp.net mvc?

asp.net asp.net-mvc-5 c# entity-framework sql

Question

I've created a controller class as below:

public class CelebrityController : Controller
{
    private MyDatabase db = new MyDatabase();

    public ActionResult Index()
    {
        var query = db.tableCelebrity.Include(t => t.tableMovie);
        return View(query.ToList());
    }
}

Now I want to do the same thing, but using a pure SQL query in the Index method. I am trying to replace code as below:

public class CelebrityController : Controller
    {
        private MyDatabase db = new MyDatabase();

        public ActionResult Index()
        {
            IEnumerable<tableCelebrity> results = db.ExecuteQuery<tableCelebrity>
            (@"SELECT c1.celebid as CelebrityID, t1.movieName as MovieName
                FROM tableCelebrity as c1, tableMovie as t1
                WHERE c1.celebid = t1.celebid");
        }
    }

But this gives me an error at the line db.ExecuteQuery<tableCelebrity>:

Error 'MyProject.Models.MyDatabase' does not contain a definition for 'ExecuteQuery' and no extension method 'ExecuteQuery' accepting a first argument of type 'MyProject.Models.MyDatabase' could be found

Is it possible with ASP.NET MVC?? If yes, then what changes I have to perform in the method?

Please help me to do that.

I am created Details method as below

public ActionResult ShortDetails(int? id, string tagname)
    {
        tblCelebrity tblcelebrity = db.tblCelebrities.SqlQuery<tblCelebrity>("SELECT * FROM dbo.tblCelebrity WHERE Celebrity_ID =" + id);

        if (tblcelebrity == null)
        {
            return HttpNotFound();
        }
        return View(tblcelebrity);
    }

And Details View accepting type as

@model MyProject.Models.tblCelebrity

I also created tblCelebrity class in my project

But `tblCelebrity tblcelebrity = db.tblCelebrities.SqlQuery("SELECT * FROM dbo.tblCelebrity WHERE Celebrity_ID =" + id); this line gives error as The non-generic method 'System.Data.Entity.DbSet.SqlQuery(string, params object[])' cannot be used with type arguments

1
5
1/15/2014 2:19:13 PM

Popular Answer

You want something similar to this :

using (var context = new BloggingContext())
{
    var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}

You can find tutorial for that here : http://msdn.microsoft.com/en-us/data/jj592907.aspx

12
1/14/2014 1:40:41 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow