Asp.Net:从类返回读者 [英] Asp.Net: Returning a Reader from a Class

查看:222
本文介绍了Asp.Net:从类返回读者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道从课程中返回读者的正确方法。



我的代码如下,但我不确定这是否正确。



此外。我不能在我的类方法中关闭连接,仍然从我的ascx页面访问它,是



好吗?



//在我的类中,我有以下方法来返回记录/ reader - 这是一个单独的记录。

 code> public SqlDataReader GetPost()
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(con_spPost,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(@ blogid,blogid);
try
{
conn.Open();
return cmd.ExecuteReader();
}
finally
{
// conn.Close();
}
}

//然后调用我的ascx中的GetPost方法

  protected void Page_Load(object sender,EventArgs e)
{

//实例化我们的类
MyClass DB = new MyClass();

//传入我们想要查看的帖子的ID
DB.PostID = Int32.Parse(Request.QueryString [p]);

///调用我们的GetPost方法
SqlDataReader reader = DB.GetPost();

//输出结果
reader.Read();
this.viewpost.InnerHtml =< span id ='post1_CreatedDate'> + reader [CreatedDate]。ToString()+< / span>< br>;
this.viewpost.InnerHtml + =< span class ='blogheads'> + reader [BlogTitle]。ToString()+< / span>< p>< p>;
this.viewpost.InnerHtml + = reader [BlogText]。ToString();
reader.Close();
}



我希望对我的代码或提示发表任何意见,谢谢。 p>

Melt

解决方案

一般来说, ,但读者的消费者需要控制所有在阅读器生命周期中使用的一次性对象。



为了做到这一点,将 IDbConnection 传递到 GetPost 方法,然后确保您的调用程序同时处理连接和读取器。 使用 关键字是最方便的方法:

  protected void Page_Load(object sender,EventArgs e){

//创建DB,获取id等。

使用(IDbConnection connection = new SqlConnection(connectionString))
using(IDataReader reader = DB.GetPost ){
reader.Read();
this.viewpost.InnerHtml = reader [BlogText]。ToString();
//用阅读器完成操作
}
}

正如其他人所指出的,这开始使用太多的数据访问基础设施来混乱您的应用程序的表示层,因此这里不适用。在您发现自己遇到性能问题或需要显示不合理的数据量之前,您不应该在表示层中处理数据读取器。只要使 DB.GetPost 返回一个字符串,并封装所有的数据访问代码。


I was just wondering about the correct way to return a reader from a class?

My code below works, but I'm unsure if this is correct.

Also. I can't close the the connection in my class method and still access it from my ascx page, is

that OK?

// In my class I have the following method to return the record/reader -- it's a single record in this case.

public SqlDataReader GetPost()
    {
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("con_spPost", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@blogid", blogid);
        try
        {
            conn.Open();
            return cmd.ExecuteReader();
        }
        finally
        {
          //  conn.Close();
        }
    }

//I then call the GetPost method in my ascx page like so:

protected void Page_Load(object sender, EventArgs e)
{

    //instantiate our class
    MyClass DB = new MyClass();

    //pass in the id of the post we want to view
    DB.PostID = Int32.Parse(Request.QueryString["p"]);

    ///call our GetPost method
    SqlDataReader reader = DB.GetPost();

   //output the result
    reader.Read();
    this.viewpost.InnerHtml = "<span id='post1_CreatedDate'>" + reader["CreatedDate"].ToString() + "</span><br>";
    this.viewpost.InnerHtml += "<span class='blogheads'>" + reader["BlogTitle"].ToString() + "</span><p><p>";
    this.viewpost.InnerHtml += reader["BlogText"].ToString();
    reader.Close();
}

I'd appreciate any comments on my code or tips, thanks.

Melt

解决方案

Generally speaking it's fine to return a reader from a method, but the reader's consumer needs to take control of all the disposable objects that will be used during the reader's lifetime.

To do this, you'd pass an IDbConnection into the GetPost method, then make sure your caller disposes both the connection and reader. The using keyword is the most convenient way to do this:

protected void Page_Load(object sender, EventArgs e) {

    // Create the DB, get the id, etc.    

    using (IDbConnection connection = new SqlConnection(connectionString))
    using (IDataReader reader = DB.GetPost(connection)) {
        reader.Read();
        this.viewpost.InnerHtml = reader["BlogText"].ToString();
        // finishing doing stuff with the reader  
    }
}

As others have pointed out, this starts to clutter your application's presentation layer with way too much data-access infrastructure - so it isn't appropriate here. Until you find yourself with a performance problem or need to display an unreasonable amount of data, you shouldn't be handling data readers in your presentation layer. Just make DB.GetPost return a string, and encapsulate all the data-access code in there.

这篇关于Asp.Net:从类返回读者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆