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

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(object sender, EventArgs e)

{

}

protected void Button2_Click(object sender, EventArgs e)

{

GridView1.DataSource = de.date();

GridView1.DataBind();

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值