在ASP.NET三层架构中使用泛型获取实体数据

来源:互联网 发布:c#网络编程 pdf 编辑:程序博客网 时间:2024/04/30 00:16

ASP.NET中使用泛型获取实体数据可以发挥更高的效率,代码简洁方便,本例采用三层架构。首先在model层中定义StuInfo实体,然后在 DAL层的SQLHelper数据操作类中定义list<>泛型查询数据库获取实体数据,最后通过BLL层的方法调用出来。具体实例如下:

一、model层中定义的StuInfo实体:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Model

{

public class StuInfo

{

private string _id;

public string Id

{

get { return _id; }

set { _id =value; }

}

private string _stuname;

public string Stuname

{

get { return _stuname; }

set { _stuname = value; }

}

private string _stuclass;

public string Stuclass

{

get { return _stuclass; }

set { _stuclass = value; }

}

}

}

二、DAL层中通过list泛型获取实体数据:

public List<StuInfo>date()

{

List<StuInfo>list = null;

cmd = new SqlCommand("select * from stuinfo",conn);

try

{

conn.Open();

dr = cmd.ExecuteReader();

list = new List<StuInfo>();

while (dr.Read())

{

StuInfo stu= new StuInfo();

stu.Id= dr["id"].ToString();

stu.Stuname= dr["stuname"].ToString();

stu.Stuclass= dr["stuclass"].ToString();

list.Add(stu);

}

return list;

}

catch (Exception)

{

return null;

}

finally

{

conn.Close();

}

}

三、在BLL层中调用DAL层的方法获取实体数据:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DAL;

using Model;

namespace BLL

{

public class StuDel

{

SQLHelper db= new SQLHelper();

public List<StuInfo>date()

{

return db.date();

}

}

}

四、在web UI层中显示实体数据经过第三步,实体数据已经添加到list泛型集合中了,那么如何显示出来呢?可以在页面上添加数据显示控件,如GridView,然后在cs代码中给它指定一个数据源,这个list泛型集合就可以作为它的数据源,让它显示数据。

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using BLL;

public partial class _Default : System.Web.UI.Page

{

StuDel de= new StuDel();

protected void Page_Load(objectsender, EventArgs e)

{

}

protected void Button2_Click(objectsender, EventArgs e)

{

GridView1.DataSource= de.date();

GridView1.DataBind();

}

}