2017-04-14 149 views
1

我试图访问我创建的数据库来显示列表。我在我的控制器中这样做。它是红色的下划线部分。它说“名称db在当前上下文中不存在”。我错过了一些东西来连接到我的代码中的数据库?控制器中的ASP.NET MVC实体框架数据库访问

using System.Web; 
using System.Web.Mvc; 
using System.IO; 
using System.Web.Helpers; 
using MIS424Assignments.Models; 

namespace MIS424Assignments.Controllers 
{ 
    [Authorize (Users="[email protected]")] 
    public class RetailController : Controller 
    { 
     // GET: Retail 
     [AllowAnonymous] 
     public ActionResult Index() 
     {    
       string sql = "Select * from Product order by newid()"; 
       List<Product> productList = db.Product.SqlQuery(sql).ToList(); 
       return View(); 
     } 
    } 
} 
+0

你能提供你收到的错误吗? –

+0

您必须在您的DBContext下执行查询。在这里了解更多关于实体框架http://www.entityframeworktutorial.net/EntityFramework4.3/add-entity-using-dbcontext.aspx –

+1

你还没有初始化数据库。请初始化您的数据库到数据库并尝试。发布你的结果,以便我们能更好地回答你。 –

回答

2

在这里尝试这种

[Authorize (Users="[email protected]")] 
public class RetailController : Controller 
{ 

    private readonly RetailStoreEntities1 db; 
    public RetailController() 
    { 
     db = new RetailStoreEntities1(); 
    } 

    // GET: Retail 
    [AllowAnonymous] 
    public ActionResult Index() 
    {    
      string sql = "Select * from Product order by newid()"; 
      List<Product> productList = db.Product.SqlQuery(sql).ToList(); 
      return View(); 
    } 
} 
0

我没有看到连接字符串。这可能是问题吗? 如果您使用EF,您是否在您的webconfig中配置了连接字符串。

我用引火烧身的,一个当我第一次开始与EF :-D

*** UPDATE **** 下面的代码将你的上下文类作为构建子中去。

让我知道这是否有助于

公共YourContextClass():基地( “RetailStoreEntities1”) {

} 
+0

我有在我的网络配置 –

+0

您是否将ConnectionString名称”RetailStoreEntities1“传递给您的数据库上下文? – 2017-04-14 17:03:04

+0

我将追加一个示例到我原来的帖子;-) – 2017-04-14 17:03:34

0

有人势必建议从存储库执行所有数据库访问,并从您的控制器调用存储库方法。 但是,要快速回答你的问题。 您的项目应该包括类与背景

public class MyContext: DbContext 
{ 
public MyContext() 
    : base("myconnstringinwebconfig") 
{} 
//more stuff here, maybe your entities.  
} 

和附近某处控制器的顶部,应该有一条线,将初始化您的上下文:

private MyContext db = new MyContext(); 

,这将解决您的错误信息。