曹永思

导航

asp.net DataReader DataTable 使用反射给给实体赋值

asp.net 使用反射给给实体赋值 

 实体类继承此基类

using System.Reflection;
using System.Data.SqlClient;
using System.Data;
namespace Model
{
    public class Base
    {
        protected bool isNull = true;
        public bool IsNull
        {
            get { return isNull; }
            set { isNull = value; }
        }
        protected void SetValue(object info)
        {
            foreach (FieldInfo fi in info.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                fi.SetValue(this, fi.GetValue(info));
            }
        }
        public void SetValue(SqlDataReader dr)
        {
            if (dr.Read())
            {
                foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (fi.Name != "isNull")
                    {
                        fi.SetValue(this, dr[fi.Name]);
                    }
                }
                this.isNull = false;
            }
            dr.Close();
        }

        public void SetValue(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {     
                foreach (DataRow row in dt.Rows)
                {
                    foreach (DataColumn column in dt.Columns)
                    {
                        FieldInfo fi = this.GetType().GetField(column.ColumnName);
                        if (fi.Name != "isNull")
                        {
                            fi.SetValue(this, row[fi.Name]);
                        }
                    } 
                } 
            }
        }

    }
}
View Code

 实体类

namespace Model
{
    public class Users: Base
    {
        protected String userid;
        public String UserId
        {
            get { return userid; }
            set { userid= value; }
        }
        protected String username;
        public String UserName
        {
            get { return username; }
            set { username= value; }
        }
    }
}
View Code

给实体类赋值

  public Users Get(String username)
        {
            Users info = new Users ();
            SqlParameter[] paras ={
                           new SqlParameter("@username",SqlDbType.NVarChar)
                            };
            paras[0].Value = username;
            SqlDataReader dr = DbHelper.ExecuteReader(CommandType.StoredProcedure, "GetUsersByUserName", paras);
            info.SetValue(dr);
            return info;
        }
View Code

 

posted on 2015-04-02 09:31  曹永思  阅读(381)  评论(0编辑  收藏  举报