【问题标题】:How can I return a Object with Data in it如何返回包含数据的对象
【发布时间】:2011-03-28 09:09:15
【问题描述】:

我知道这可能很简单,我知道我发布的代码是错误的,但我想我已经接近了。

我想从文件 pageDAL.cs 中获取下面的函数,以返回包含我传入的任何 pageID 的值的对象页面。如果我不需要使用 DataSet 或 DataTable 那很好。最好的方法是什么?

 public page getPage(int _pageID)
    {
      DataTable dt = new DataTable;
      using (SqlDataAdapter da = new SqlDataAdapter("select PageID,ParentID,CategoryID,Name,PageHTMLContent,NavigationText,TopMenu,SubMenu,DisplayOrder,Active from Page where PageID = " + _PageID, ConnectionStrings.StaceysCakes))
      {
        da.Fill(dt);
        dt.AsEnumerable().Select(r => page)
      {
        page myPageOBJ = new page();
        myPageObj.PageID = r.Field<int>("PageID"),
        ParentID = r.Field<int>("ParentID"),
        CategoryID = r.Field<int>("CategoryID"),
        Name = r.Field<string>("Name"),
        PageHTMLContent = r.Field<string>("PageHTMLContent"),
        NavigationText = r.Field<string>("NavigationText"),
        TopMenu = r.Field<bool>("TopMenu"),
        SubMenu = r.Field<bool>("SubMenu"),
        DisplayOrder = r.Field<int>("DisplayOrder"),
        Active = r.Field<bool>("Active"),
      });
      }
     return page;
    }

page.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace sc2.Models.page
{  
  public class page
  {
    public int PageID { get; internal set; }
    public int ParentID { get; internal set; }
    public int CategoryID { get; internal set; }
    public string Name { get; internal set; }
    public string PageHTMLContent { get; internal set; }
    public string NavigationText { get; internal set; }
    public bool TopMenu { get; internal set; }
    public bool SubMenu { get; internal set; }
    public int DisplayOrder { get; internal set; }
    public bool Active { get; internal set; }

    public page()
    {
    }

  }
}

pageBLL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
//using sc2.Models;

namespace sc2.Models.page
{
  public class pageBLL
  {

    pageDAL myPageDAL = new pageDAL();


    public pageBLL(){
    }

    public page getPage()
    {
      page PageOBJ = new page();
      return PageOBJ;
    }

    public page getPage(int _pageID)
    {
      return myPageDAL.getPage(_pageID);
    }

    public string save(page _page)
    {
      return myPageDAL.save(_page);
    }


    public List<page> Select()
    {
      return (myPageDAL.Select());
    }

    public List<page> Select(string _OrderBy)
    {
      return (myPageDAL.Select(_OrderBy));
    }

    public DataSet Get(int _PageID)
    {
      return (myPageDAL.Get(_PageID));
    }

    public void DeletePage(int _PageID)
    {
      myPageDAL.DeletePage(_PageID);
    }


  }
}

pageDLL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;

namespace sc2.Models.page
{
  public class pageDAL
  {

    public pageDAL()
    {
    }

    // List Order By
    public List<page> Select(string _OrderBy)
    {
      string sqlStatement = _OrderBy;
      return All(sqlStatement);
    }


    // Select List of Objects
    public List<page> Select()
    {
      string sqlStatement = "DisplayOrder";
      return All(sqlStatement);
    }

    // Return List of Objects
    public List<page> All(string _sqlStatement)
    {
      var sqlResults = new DataTable();
      string sqlStatement = "select PageID,ParentID,CategoryID,Name,PageHTMLContent,NavigationText,TopMenu,SubMenu,DisplayOrder,Active from page";
      if (!String.IsNullOrEmpty(_sqlStatement))
      {
        sqlStatement += " Order By " + _sqlStatement;
      }
      using (SqlConnection conn = new SqlConnection(ConnectionStrings.StaceysCakes))
      {
        using (SqlCommand command = new SqlCommand(sqlStatement, conn))
        {
          var adapter = new SqlDataAdapter(command);
          adapter.Fill(sqlResults);
        }
      }

      return sqlResults.AsEnumerable().Select(r => new page()
      {
        PageID = r.Field<int>("PageID"),
        ParentID = r.Field<int>("ParentID"),
        CategoryID = r.Field<int>("CategoryID"),
        Name = r.Field<string>("Name"),
        PageHTMLContent = r.Field<string>("PageHTMLContent"),
        NavigationText = r.Field<string>("NavigationText"),
        TopMenu = r.Field<bool>("TopMenu"),
        SubMenu = r.Field<bool>("SubMenu"),
        DisplayOrder = r.Field<int>("DisplayOrder"),
        Active = r.Field<bool>("Active"),
      }).ToList();


    }

    public page getPage(int _pageID)
    {
      DataTable dt = new DataTable;
      using (SqlDataAdapter da = new SqlDataAdapter("select PageID,ParentID,CategoryID,Name,PageHTMLContent,NavigationText,TopMenu,SubMenu,DisplayOrder,Active from Page where PageID = " + _PageID, ConnectionStrings.StaceysCakes))
      {
        da.Fill(dt);
        dt.AsEnumerable().Select(r => page)
      {
        page myPageOBJ = new page();
        myPageObj.PageID = r.Field<int>("PageID"),
        ParentID = r.Field<int>("ParentID"),
        CategoryID = r.Field<int>("CategoryID"),
        Name = r.Field<string>("Name"),
        PageHTMLContent = r.Field<string>("PageHTMLContent"),
        NavigationText = r.Field<string>("NavigationText"),
        TopMenu = r.Field<bool>("TopMenu"),
        SubMenu = r.Field<bool>("SubMenu"),
        DisplayOrder = r.Field<int>("DisplayOrder"),
        Active = r.Field<bool>("Active"),
      });
      }
     return page;
    }

    // (DataSet) get
    public DataSet Get(int _PageID)
    {
      using (SqlDataAdapter da = new SqlDataAdapter("select PageID,ParentID,CategoryID,Name,PageHTMLContent,NavigationText,TopMenu,SubMenu,DisplayOrder,Active from Page where PageID = " + _PageID, ConnectionStrings.StaceysCakes))
      {
        DataSet ds = new DataSet();
        da.Fill(ds, "Pages");
        return (ds);
      }
    }

    // Save
    public string save(page _page)
    {
      string errorMessage = "";

      if (_page.CategoryID == 0)
      {
        InsertPage(_page.Name, _page.PageHTMLContent, _page.NavigationText, _page.TopMenu, _page.SubMenu, _page.DisplayOrder, _page.Active);
      }
      else
      {
        UpdatePage(_page.CategoryID, _page.Name, _page.PageHTMLContent, _page.NavigationText, _page.TopMenu, _page.SubMenu, _page.DisplayOrder, _page.Active);
      }
      return errorMessage;
    }


    // Insert Page
    public string InsertPage(string _Name, string _PageHTMLContent, string _NavigationText, bool _TopMenu, bool _SubMenu, int _DisplayOrder, bool _Active)
    {
      SqlConnection myConnection = new SqlConnection(ConnectionStrings.StaceysCakes);
      string SqlStatement = "insert into Page (Name,PageHTMLContent,NavigationText,TopMenu,SubMenu,DisplayOrder,Active) values ('"
        + _Name + "','"
        + _PageHTMLContent + "','"
        + _NavigationText + "','"
        + _TopMenu + "','"
        + _SubMenu + "',"
        + _DisplayOrder + ",'"
        + _Active + "');";
      string errorMessage = "";
      try
      {
        SqlCommand myCommand = new SqlCommand(SqlStatement);
        myCommand.Connection = myConnection;
        myConnection.Open();
        myCommand.ExecuteNonQuery();
      }
      catch (Exception e)
      {
        errorMessage = "There was an error with the database insert.";
        Trace.Write("Database unavailable with Message: ", e.Message);
        Trace.Write("Stack Trace: ", e.StackTrace);
        // Throw the exception higer for logging and notification
        throw;

      }

      // Clean up any loose ends.
      finally
      {
        myConnection.Close();
      }

      // Return the error message if there is one.
      return errorMessage;

    }

    // Update Page
    public string UpdatePage
      (int _PageID,
       string _Name,
       string _PageHTMLContent,
       string _NavigationText,
       bool _TopMenu,
       bool _SubMenu,
       int _DisplayOrder,
       bool _Active)
    {
      string SqlStatement = "UPDATE Page SET Name='" + _Name + "', PageHTMLContent='" + _PageHTMLContent + "', NavigationText='" + _NavigationText + "', TopMenu='" + _TopMenu + "', SubMenu='" + _SubMenu + "', DisplayOrder=" + _DisplayOrder + ", Active='" + _Active + "' where PageID = '" + _PageID + "'";
      SqlConnection myConnection = new SqlConnection(ConnectionStrings.StaceysCakes);
      string errorMessage = "";
      try
      {
        SqlCommand myCommand = new SqlCommand(SqlStatement);
        myCommand.Connection = myConnection;
        myConnection.Open();
        myCommand.ExecuteNonQuery();
      }
      catch (Exception e)
      {
        errorMessage = "There was an error with the database update.";
        Trace.Write("Database unavailable with Message: ", e.Message);
        Trace.Write("Stack Trace: ", e.StackTrace);
        // Throw the exception higer for logging and notification
        throw;
      }

      // Clean up any loose ends.
      finally
      {
        myConnection.Close();
      }

      // Return the error message if there is one.
      return errorMessage;
    }

    // Delete Page
    public string DeletePage(int _PageID)
    {

      string SqlStatement = "Delete from Page where PageID = '" + _PageID + "'";

      SqlConnection myConnection = new SqlConnection(ConnectionStrings.StaceysCakes);
      string errorMessage = "";
      try
      {
        SqlCommand myCommand = new SqlCommand(SqlStatement);
        myCommand.Connection = myConnection;
        myConnection.Open();
        myCommand.ExecuteNonQuery();
      }
      catch (Exception e)
      {
        errorMessage = "There was an error with the database delete.";
        Trace.Write("Database unavailable with Message: ", e.Message);
        Trace.Write("Stack Trace: ", e.StackTrace);
        // Throw the exception higer for logging and notification
        throw;
      }

      // Clean up any loose ends.
      finally
      {
        myConnection.Close();
      }

      // Return the error message if there is one.
      return errorMessage;
    }
  }
}

【问题讨论】:

标签: c# asp.net oop


【解决方案1】:

看看 SqlDataReader 类。它比 SqlDataAdapter 和 DataTable 简单得多,开销也更少。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

另外,看here

var results = new List<page>();
string queryString = "SELECT PageID,ParentID...";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        page p= new page();
        p.PageID = reader["PageID"]; 
        //...
        results.Add(p);
    }
    reader.Close();
}
return results;

【讨论】:

    【解决方案2】:

    你不只需要返回 myPageOBJ,而不是你的 getPage() 方法中的页面吗?

    您还需要在分配给 myPageOBJ 成员之前使用“myPageObj.”。您可能还想检查对象初始化器以使页面对象的设置更清晰。

    【讨论】:

      【解决方案3】:

      您应该避免使用SQL Injection,并考虑使用能够为您提供分页结果的 ORM,例如 NHibernate 或 Fluent NHibernate,例如:How can you do paging with NHibernate?

      上手 NHibernate 需要一点时间,但是一旦你上手了,事情就会变得更容易和简单。

      【讨论】:

      • 我正在研究学习 LINQ、Entity 和(NHibernate 和/或 Fluent NHibernate)。我目前正在获得报酬来学习 DotNet,然后在 SharePoint 之后,所以一旦我觉得我已经学会了足够的 DotNet 以从事不同的工作......(如果他们使用这些不同风格的获取中的任何一种)工作完成。)
      • 我希望学习 .Net 是有报酬的,我必须免费学习 :)
      猜你喜欢
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2017-07-15
      • 2015-12-04
      • 1970-01-01
      • 2013-10-02
      • 2015-07-02
      相关资源
      最近更新 更多