我创建了一个 Controller 类,如下所示:

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

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

现在,我想做同样的事情,但是在Index方法中使用纯SQL查询。
我正在尝试替换如下代码:
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");
        }
    }

但这在db.ExecuteQuery<tableCelebrity>行给了我一个错误:



ASP.NET MVC有可能吗?如果是,那么我必须在方法中执行哪些更改?

请帮我做到这一点。
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);
    }

并且“详细信息 View ”接受类型为
@model MyProject.Models.tblCelebrity

我还在项目中创建了tblCelebrity类

但是`tblCelebrity tblcelebrity = db.tblCelebrities.SqlQuery(“SELECT * FROM dbo.tblCelebrity WHERE Celebrity_ID =” + id);
这行给出错误为
非泛型方法'System.Data.Entity.DbSet.SqlQuery(string,params object [])'不能与类型参数一起使用

最佳答案

您想要类似以下内容:

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

您可以在这里找到相关的教程:
http://msdn.microsoft.com/en-us/data/jj592907.aspx

关于c# - 如何在ASP.NET MVC中编写纯SQL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21114965/

10-09 13:31