【问题标题】:Separating Data-Access Code Into a Distinct Tier将数据访问代码分成不同的层
【发布时间】:2014-12-10 00:56:36
【问题描述】:

我正在尝试将此功能分离为传统的 3 层模式,但遇到了一些困难。

数据访问不是我经常使用的东西,我想要一些指导。

我从code from this blog 开始,到目前为止我所做的如下。我正在将返回类型转换为SqlDataReader,现在我已经注释掉了需要分离的代码。

// This is the DAL layer:
public SqlDataReader DownloadFile(int fileId)
{
    //int id = int.Parse((sender as LinkButton).CommandArgument);
    //byte[] bytes;
    //string fileName, contentType;
    //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    //using (SqlConnection con = new SqlConnection(constr))
    //{
        cmd.CommandText = "SELECT  [fileId],[fileName],[fileData],[postedBy] FROM  [dbo].[FilesLibrary] where fileId=@Id";
        cmd.Parameters.AddWithValue("@Id", fileId);
        cmd.Connection = cmd.Connection;

        try
        {
            cmd.Connection.Open();

            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                //sdr.Read();
                //bytes = (byte[])sdr["Data"];
                //contentType = sdr["ContentType"].ToString();
                //fileName = sdr["Name"].ToString();
                return sdr;
            }
        }
        catch (Exception ex)
        {
            cmd.Connection.Close();
            throw;
        }
    //}
    //Response.Clear();
    //Response.Buffer = true;
    //Response.Charset = "";
    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
    //Response.ContentType = contentType;
    //Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    //Response.BinaryWrite(bytes);
    //Response.Flush();
    //Response.End();
}

// The BL is below:        
public SqlDataReader GetFileDownload(int fileId)
{
    try
    {
        dsGetFiles files = new dsGetFiles();
        return files.DownloadFile(fileId);
    }
    catch (Exception ex) { throw ex; }
}

// The code file is as follows:
protected void DownloadFile(object sender, EventArgs e)
{
    int id = int.Parse((sender as LinkButton).CommandArgument);
    byte[] bytes;
    string fileName, contentType;

    GetFiles fileInfo = new GetFiles();
    fileInfo.GetFileDownload(id);

    // Here I don't know what to do with the fileInfo object and how to get data out of it.
    //sdr.Read();
    //bytes = (byte[])sdr["fileData"];
    //contentType = sdr["ContentType"].ToString();
    //fileName = sdr["fileName"].ToString();


    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = contentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

【问题讨论】:

  • 如果有不清楚的地方请告诉我!

标签: c# asp.net ado.net 3-tier


【解决方案1】:
// This is the DAL layer:
public DataSet DownloadFile(int fileId)
{
    //I don't know from where you are taking your command and connection, but I will assume that this is working correctly, I don't like this method ! Also close a connection only on catch block? Your are using only one connection ? If you tell me that this method is not working I will re write it too. 

cmd.CommandText = "SELECT  [fileId],[fileName],[fileData],[postedBy] FROM  [dbo].[FilesLibrary] where fileId=@Id";
cmd.Parameters.AddWithValue("@Id", fileId);
cmd.Connection = cmd.Connection;

try
{
    cmd.Connection.Open();

    DataSet dst = new DataSet();
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    {
        adapter.Fill(dst, "FilesLibary");        
    }

    return dst;
}
catch (Exception ex)
{
    cmd.Connection.Close();
    throw;
}


}

// The BL is below:        
public byte[] GetFileDownload(int fileId)
{
    try
    {
        DataSet fileDst = new DownloadFile();// method from DA layer
        return (byte[])fileDst.Tables[0].Rows[0]["fileData"];
    }
    catch (Exception ex) { throw ex; }
}



protected void DownloadFile(object sender, EventArgs e)
{
    int id = int.Parse((sender as LinkButton).CommandArgument);
    byte[] bytes = fileInfo.GetFileDownload(id);

//Now do your magic, if you want to have fileName in the business logic you should take GetFileDownload should return DataSet. After that take byte[] and fileName. I will write the fileName to be test for this case to not re write everything here !

Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=Test");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

请注意:您的数据访问层非常糟糕。你应该重新写。就像你在DataLayer中改变你的方法后看到的,你甚至不需要BO逻辑方法,因为你的数据层将重新运行所需的DataSet,你可以在protected void DownloadFile(object sender, EventArgs e)中调用

在这个问题中我写了一点完整的数据层类,如果你愿意,可以查看: checking user name or user email already exists

附言。抱歉,左括号和结束括号的格式问题!

【讨论】:

  • 非常清楚。使用 Dataset 类型非常有意义。那么您将如何重写 DataLayer?请注意,我通常在 DAL 中使用 sproc 而不是 sql 语句,也许这就是您所指的。
  • @Risho 数据层应该更抽象。该层永远不应返回特定对象的数据,就像您的情况一样。就像我说的,您可以查看我在另一个 stackoverflow 问题中写的答案。我在答案中发布了一个链接。
  • @Risho 制作数据层的一种方法是仅将 SqlCommand 提供给层。另外,如果答案帮助您接受它:)
猜你喜欢
  • 1970-01-01
  • 2018-03-05
  • 2013-04-09
  • 1970-01-01
  • 2010-09-16
  • 2021-07-16
  • 2012-11-24
  • 1970-01-01
  • 2012-07-06
相关资源
最近更新 更多