2014-02-11 113 views
0

我在做c#中的3層體系結構的基本示例。我爲數據和業務層創建了兩個dll。此外,我在業務層代碼中使用數據層dll。並且,業務dll和在表示層的數據訪問的DLL(這是一個winform應用程序)。現在,正在執行的表示層代碼時,一個異常即將它說:無法從數據層讀取數據

數據庫 「d:\ 11feb \實踐\ 3TIER \ PresentationLayer \ PresentationLayer \ bin \ Debug \ Data.mdf' 不存在。

我在數據層創建了我的數據庫Data.mdf。 我將數據庫文件複製到異常中提到的位置,並且應用程序成功執行。但是我希望從我的數據層訪問數據庫。

數據層郵編:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 
using System.Data.SqlClient; 

namespace DataAccessLayer 
{ 
    public class DataAccess 
    { 
     public DataTable dataRead() 
     { 

      SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data.mdf;Database=Data;Integrated Security=True;User Instance=True"); 
      DataTable dt = new DataTable(); 
      con.Open(); 
      SqlCommand cmd = new SqlCommand("select ID,Name from datatable", con); 
      try 
      { 
       SqlDataReader rd = cmd.ExecuteReader(); 
       dt.Load(rd); 
       return dt; 
       } 
       catch 
       { 
        throw; 
       } 

      } 
     } 
    } 

業務層郵編:

 using System; 
     using System.Collections.Generic; 
     using System.Linq; 
     using System.Text; 
     using DataAccessLayer; 
     using System.Data; 

     namespace BusinessLogicLayer 
     { 
      public class BusinessLogic 
      { 
       DataAccess dataAccess = new DataAccess(); 

       public DataTable getPersons() 
       { 
        try 
        { 
         return dataAccess.dataRead(); 
        } 
        catch { throw; } 
       } 
      } 
     } 

表示層郵編:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using BusinessLogicLayer; 

namespace PresentationLayer 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      try 
      { 
       BusinessLogic BusinessLogic = new BusinessLogic(); 
       this.dataGridView1.DataSource = BusinessLogic.getPersons(); 
      } 
      catch 
      { 
       MessageBox.Show("Error Occurred"); 
      } 
     } 
    } 
} 
+0

右鍵單擊數據庫並查看連接字符串並在代碼中使用它。 – Sachin

回答

1

的問題是,你在溶液Data.mdf但是當應用程序運行時,它會嘗試查找bin目錄中的mdf文件。點擊解決方案中的Data.mdf文件。轉到其屬性(按F4鍵),然後查看「複製到輸出目錄」屬性,然後將該值更改爲始終複製。

還檢查您的連接字符串。