2017-04-14 123 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(); 

,這將解決您的錯誤信息。