设计最高!自定义实体类

来源:互联网 发布:摄像头搜索软件 编辑:程序博客网 时间:2024/06/06 17:10
参考:
http://www.microsoft.com/china/msdn/library/webservices/asp.net/CustEntCls.mspx?pf=true
 
Dataset虽然支持离线访问数据,但是他缺点很多(不抽象,不OO,弱类型,内存占用大,速度慢),于是就有了自定义实体类(datareader+实体类 实现),小小实现下:

 

实体类
public class User
 {
  private int userId;   //3个属性
  private string userName;
  private string password;
  public int UserId
   {
    get { return userId; }
    set { userId = value; }
   }
  public string UserName
   {
    get { return userName; }
    set { userName = value; }
   }
  public string Password
   {
    get { return password; }
    set { password = value; }
   }
public User() {}
public User(int id, string name, string password) {
this.UserId = id;
this.UserName = name;
this.Password = password;
 }
}

 

实体类集合
public class UserCollection:CollectionBase
//继承CollectionBase类,工作原理是将所有类型的对象都存储在专有Arraylist中
 {
  public User this[int index] //引索器
   {
    get {return (User)List[index];}
    set {List[index] = value;}
   }
  public int Add(User value)
  //将对象添加到CollectionBase的结尾处,返回引索值
   {
    return (List.Add(value));
   }
  public int IndexOf(User value)
  //查找某对象,返回该对象引索值
   {
    return (List.IndexOf(value));
   }
  public void Insert(int index, User value)
  /将对象插入CollectionBase的指定索引处
   {
    List.Insert(index, value);
   }
  public void Remove(User value)
  //从CollectionBase中移除某对象
   {
    List.Remove(value);
   }
 public bool Contains(User value)
 //CollectionBase中是否包含某对象,返回true/false
   {
    return (List.Contains(value));
   }
 }

 

将datareader数据转成user对象
public User PopulateUser(IDataRecord dr) 
//IDataRecord是所有(Sql/OleDb)DataReader实现的接口
 {
  User user = new User();
  user.UserId = Convert.ToInt32(dr["UserId"]);
  if(dr["UserName"] != DBNull.Value) //检查null
   {
    user.UserName = Convert.ToString(dr["UserName"]);  
   }
  user.Password = Convert.ToString(dr["Password"]);
  return user;
 }

 

单个实体映射
public User GetUser(int userId)
 {
  User user = null;
  string strSql = "Select * From [User] Where UserID=@UserID";
  SqlParameter[] parms = new SqlParameter[1];
  parms[0] = new SqlParameter("@UserID", SqlDbType.Int);
  parms[0].Value = userid;           
  SqlConnection conn = new SqlConnection(XXXXX数据库连接);
  SqlCommand command = new SqlCommand(strSql,conn);
  SqlDataReader dr = null;
  conn.Open();
  dr = command.ExecuteReader();
  if(dr.Read())
   {
    user = PopuplateUser(dr);   //把datareader数据转成user对象
   }
  conn.Close();
  return user;
 }

 

实体集合映射
public UserCollection GetAllUser()
 {
  UserCollection users = new UserCollection();
  string strSql = "Select * From [User]";
  SqlConnection conn = new SqlConnection(XXXXX数据库连接);
  SqlCommand command = new SqlCommand(strSql,conn);
  SqlDataReader dr = null;
  conn.Open();
  dr = command.ExecuteReader();
  while (dr.Read())
   {
    users.Add(PopuplateUser(dr));
    //把datareader数据转成单个user对象,再用Add方法添进集合
   }
  dr.Close();
  conn.Close();
  return users;
 }

 

实体类的大致实现就是这样,同时我们也可以在实体类中添加一些常用方法,如:
public User FindUserById(int userId)
 {
  foreach (User user in List)
   {
    if (user.UserId == userId)
     {
      return user;
     }
   }
  return null;
 }

 

同时实体类集合,可以轻松实现数据绑定(因为CollectionBase类实现了用于绑定的Ilist接口)
UserCollection users = DAL.GetAllUsers();
repeater.DataSource = users;
repeater.DataBind();
<asp:Repeater onItemDataBound="r_IDB" ID="repeater" Runat="server">
 <ItemTemplate>
  <asp:Label ID="userName" Runat="server">
   <%# DataBinder.Eval(Container.DataItem, "UserName") %>
  </asp:Label>
 </ItemTemplate>
</asp:Repeater>

 

管理关系(Role类或RoleCollection类也是自定义实体/集合)实体之间也存在关系,使用对象时,关系只是对另一个对象的引用
public class User
 {……………………
  private Role role;  //添加一个Role属性,表示单个Role实体
  public Role Role
   {
    get {return role;}
    set {role = value;}
   }
 }
或者:
public class User
 {……………………
  private RoleCollection roles; //添加一个RoleCollection属性,表示Role的集合
  public RoleCollection Roles
   {
    get
     {
      if(roles == null)
       {roles = new RoleCollection();}
      return roles;
     }
    }
 }
映射的例子
public User GetUserRoleId()
 {
  User user = new User();//若有PopulateUser方法,则User user=null;
  user.Role = new Role();//若用RoleCollection属性,则这句不写
  string strsql = "select User.UserId,Role.RoleId from User,Role where User.UserId=Role.RoleId";
  SqlConnection conn = new SqlConnection(XXXX数据库连接);
  SqlCommand command = new SqlCommand(strsql, conn);
  SqlDataReader dr = null;
  conn.Open();
  dr = command.ExecuteReader();
  while(dr.Read())
   {
    user.UserId=Convert.ToInt32(dr["UserId"]);//或user = PopulateUser(dr);
    user.Role.RoleId=Convert.ToInt32(dr["RoleId"]);
    //或user.Roles.Add(PopulateRole(dr));
   }           
  dr.Close();
  conn.Close();
  return user;
 }

 

会了以上内容就可轻松使用三层,MVC等等架构,同时这也是ORM的基础