【问题标题】:Unable to read data from data layer无法从数据层读取数据
【发布时间】: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");
            }
        }
    }
}

【问题讨论】:

  • 右键单击数据库并查看连接字符串并在您的代码中使用它。

标签: c# .net dll 3-tier


【解决方案1】:

问题是您在解决方案中添加了 Data.mdf,但是当应用程序运行时,它会尝试在 bin 目录中查找 mdf 文件。单击解决方案中的 Data.mdf 文件。转到其属性(按 F4),然后查找属性“复制到输出目录”,然后将值更改为始终复制。

同时检查您的连接字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多