2011-10-15 62 views
3

我遵循MVC 3的教程,並做這種情況下特定的錯誤:

實體框架拋出異常 - 網絡相關的或發生

製造4類和DBClass:
User [有] Website的列表s [有a] Page s的列表[有a] Comment s的列表[每個標記的詞是其自己的一類。

於是,我做了一個叫UserDataBaseDB這樣類:

public partial class UserDataBaseDB : DbContext 
    { 
     public DbSet<User> Users { get; set; } 

     public UserDataBaseDB() 
      : base(@"UserDataBaseDB") 
     { 
      if (this.Database.Exists()) 
      { 
       try 
       { 
        this.Database.CompatibleWithModel(false); 
       } 
       catch (InvalidOperationException) 
       { 
        this.Database.Delete(); 
       } 
      } 

      if (!this.Database.Exists()) 
      { 
       this.Database.Create(); 
       Seed(); 
      } 
     } 

     private void Seed() 
     { 
      var Mark = new User(); 
      Mark.ID = 0; 
      Mark.MD5Pass = "4297f44b13955235245b2497399d7a93"; 
      Mark.UserName = "Admin"; 

      var Troll = new Comment(); 
      Troll.CommentData = "Fake!"; 
      Troll.Writer = Mark; 

      var Site = new Website(); 
      Site.Name = "Admin Site"; 

      Site.Pages.ElementAt(0).Data = "Awesome website!"; 
      Site.Pages.ElementAt(0).Comments.Add(Troll); 

      Mark.Websites.Add(Site); 

      Users.Add(Mark); 
     } 
     public static UserDataBaseDB Create() 
     { 
      return new UserDataBaseDB(); 
     } 
     public User FindUserByID(int id) 
     { 
      return (from item in this.Users 
        where item.ID == id 
        select item).SingleOrDefault(); 
     } 

然後,我添加了ControllerView,並導航到http://localhost:40636/Main,我看到了這條消息:

與SQL Server建立連接時發生網絡相關或實例特定的錯誤。服務器未找到或無法訪問。驗證實例名稱是否正確,並將SQL Server配置爲允許遠程連接。 (提供者:SQL網絡接口,錯誤:26 - 錯誤定位服務器/實例指定)

Line 14:    : base(@"UserDataBaseDB") 
Line 15:   { 
Line 16:    **if (this.Database.Exists())** 
Line 17:    { 
Line 18:     try 

讓標線是紅線。

我試圖重新安裝實體框架,也嘗試EFCodeFirst,試圖讓我自己的SqlDataBase並給它連接字符串,但沒有任何工作。

有誰知道什麼是解決方案?謝謝!

PS:我在Win7 64位機器上使用VS Ultimate SP1。

+0

什麼是你的連接字符串來連接數據庫?你的工作站能夠連接到sql服務器嗎? – ysrb

回答

3

這可能是一個連接字符串的問題,但是我確實看到你正嘗試播種信息並在構造函數中完全使用上下文,我強烈建議你不要這樣做。 您可以實現OnModelCreating方法,並在那裏嘗試初始化代碼,或者在應用程序啓動時更好。由於初始化只是從這一點開始,所以在構造函數中被卡住似乎並不正確。

坐落於

 
if (this.Database.Exists()) 

斷點是否錯誤行後立即發生?如果是這樣,三重檢查你的連接字符串。你是否在一個項目中擁有你的代碼,或者破解了?確保你正在檢查你的根web項目的web.config中的連接字符串,而不是任何組件的app.config,如果你碰巧使用這種設計。

每次您從代碼優先等更改您是否更改您的連接字符串?代碼優先連接字符串是根據您的上下文類命名的,並且很簡單:

 

<add name="UserDataBaseDB" connectionString="Data Source=|DataDirectory|test.sdf" providerName="System.Data.SqlServerCe.4.0" /%gt; 
 

這當然使用SQLCe4。SQL服務器將

 

<add name="UserDataBaseDB" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDbName;Integrated Security=True;Pooling=False" /%gt; 
 

或在APP_DATA

 

<add name="UserDataBaseDB" providerName="System.Data.SqlClient" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\YourDatabase.mdf;User Instance=true" /%gt; 
 
+0

謝謝,這工作。儘管我在另一個問題上發佈了另一個從網站上閱讀的問題。 –

相關問題