【发布时间】:2014-03-08 21:13:02
【问题描述】:
我在 c# 中做了一个 3 层架构的基本示例。我为数据和业务层创建了两个 dll。此外,我在业务层代码中使用数据层 dll。并且,表示层中的业务 dll 和数据访问 dll(这是一个winform应用程序)。现在,当执行表示层代码时,会出现一个异常:
数据库 'D:\11feb\practice\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");
}
}
}
}
【问题讨论】:
-
右键单击数据库并查看连接字符串并在您的代码中使用它。