2016-12-24 135 views
0

我在Visual Studio 2015中從我的數據庫生成了一個ADO.NET數據模型,myEntities.Context.cs中生成的類名爲myEntities,並從DbContext繼承。如何從Web表單中的代碼訪問實體框架數據模型?

我想通過LINQ從MyPage.cs後面代碼中的模型中提取對象數據。

從我的書和教程中,我可以看到爲了做到這一點,您創建了模型類的實例,在我的示例中爲myEntities並對其運行LINQ查詢。

但是,當我嘗試實例這個類時,它沒有找到。該類是名稱空間MyAppName.App_Code中的public,並且MyPage.cs位於命名空間MyAppName中。

我似乎無法在MyPage.cs的代碼中包含MyAppName.App_Code命名空間,Visual Studio告訴我這是多餘的,後面的代碼仍然沒有看到或接受類myEntities

編輯: 更加清晰: 在App_Code文件夾MyEntities.Context.cs

namespace MyApp.App_Code 
{ 
using System; 
using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 

public partial class MyEntities : DbContext 
{ 
    public MyEntities() 
     : base("name=MyEntities") 
    { 
    } 
}} 

MyPage.cs

namespace MyApp 
{ 
public partial class _default : System.Web.UI.Page 
{ 
    public IQueryable ListView_GetData() 
    { 
     //can't use the MyEntities class here, tried to add the 
     //MyApp.App_code namespace above, still did't work 
     var data = MyEntities(); 

     //my LINQ operations 

     return null; 
    } 
}} 
+1

您能否提供您的代碼示例?您是先使用數據庫還是先使用代碼的方法? – timothyclifford

+0

數據庫第一,謝謝 –

+1

你應該在這裏閱讀'App_Code'部分https://msdn.microsoft.com/en-us/library/ex526337.aspx。我建議將這個代碼移到'App_Code'文件夾之外的一個名爲'Data'或類似文件夾的文件夾中,然後再次嘗試引用。 – timothyclifford

回答

1

的背後代碼從Microsoft documentation

App_Code中的代碼f舊版本會在您的 應用程序中自動引用。

把你DbContextApp_Code意味着它會自動提供您的應用程序的任何地方沒有一個明確的參考。所以,你就可以這樣寫:

var exampleTableEntities = MyEntities.ExampleTableEntities; 

如果你想要一個明確的參考,我會建議將您的DbContextApp_Code文件夾到一個名爲DataDomain文件夾或類似的東西。然後從您的代碼文件中引用。

相關問題