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");
}
}
}
}
右键单击数据库并查看连接字符串并在代码中使用它。 – Sachin