读书人

写了个Record类,求一上

发布时间: 2012-12-26 14:39:28 作者: rapoo

写了个Record类,求高手指点一下!


public class Record<T>
where T:class
{
private System.Collections.Generic.Dictionary<string, object> m_Record = null;

private static readonly System.Collections.Generic.Dictionary<Entities.RecordMapping,System.Reflection.PropertyInfo> PatternRecordMappingList;

static Record()
{
Record<T>.PatternRecordMappingList = new Dictionary<RecordMapping, System.Reflection.PropertyInfo>();
Type PatternType = typeof(T);
System.Reflection.PropertyInfo[] PatternTypeProperties = PatternType.GetProperties();
foreach (var Item in PatternTypeProperties)
{
object[] Result = Item.GetCustomAttributes(true);
foreach (var Mapping in Result)
{
if (Mapping.GetType() == typeof(Entities.RecordMapping))
Record<T>.PatternRecordMappingList.Add(Mapping as Entities.RecordMapping,Item);
}
}
}

public Record(System.Data.IDataReader Reader)
{
this.Initialize(Reader);
}

protected void Initialize(System.Data.IDataReader Reader)
{
object c = Reader[0];
this.m_Record = new Dictionary<string, object>(Reader.FieldCount);
for (int Index = 0; Index < Reader.FieldCount; Index++)
{
this.m_Record.Add(Reader.GetName(Index), Reader[Index]);
}
}

public T Entity()
{
Type EntityType = typeof(T);


T EntityObject = Activator.CreateInstance(EntityType) as T;
foreach (var Item in Record<T>.PatternRecordMappingList)
{
if (this.m_Record[Item.Key.RecordName] is DBNull)
continue;
Item.Value.SetValue(EntityObject, this.m_Record[Item.Key.RecordName], null);
}
return EntityObject;
}
}


[最优解释]
我写了个三层的
1 用户接口层
2 //构建实体对象student并赋值
3 private void btnSave_Click(object sender, EventArgs e)
4 {
5 //验证是否输入了必要的信息
6 if (txtUserName.Text.Equals(String.Empty)) // 验证是否输入了用户名
7 {
8 MessageBox.Show("请输入用户名", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
9 return;
10 }
11 if (txtPassword.Text.Equals(String.Empty)) // 验证是否输入了密码
12 {
13 MessageBox.Show("请输入密码", "输入提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
14 return;
15 }
16 if (txtPswAgain.Text.Equals(String.Empty)) // 验证是否输入了确认密码
17 {
18 MessageBox.Show("请输入确认密码", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
19 return;
20 }
21 if (!txtPassword.Text.Equals(txtPswAgain.Text)) // 验证两次密码是否一致


22 {
23 MessageBox.Show("两次输入的密码不一致", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
24 return;
25 }
26 if (!radActive.Checked && !radInactive.Checked) // 验证是否选择了用户状态
27 {
28 MessageBox.Show("请设置用户的状态", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
29 return;
30 }
31 if (txtName.Text.Equals(String.Empty)) // 验证是否输入了姓名
32 {
33 MessageBox.Show("请输入用户姓名", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
34 return;
35 }
36 if (cboClass.Text.Equals(String.Empty)) // 验证是否选择了用户的班级
37 {
38 MessageBox.Show("请输入选择用户班级", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
39 return;
40 }
41 //创建学员信息对象
42 Student student = new Student();
43 // 获取要插入数据库的每个字段的值
44 student.LoginId = txtUserName.Text.Trim();
45 student.LingPwd = txtUserName.Text.Trim();
46 student.StudentName = txtName.Text.Trim();
47 student.StudentNO = txtStudentNo.Text.Trim();
48 // 班级id
49 int classID =
classManager.GetClassIDByClassName(this.cboClass.Text.Trim());
50 student.ClassID = classID;


51 // 根据选择的状态设置状态id
52 string userStateId =
radActive.Checked ? (string)radActive.Tag : (string)radInactive.Tag;
53 student.UserStateId = Convert.ToInt32(userStateId);
54 student.Sex = rdoMale.Checked ? rdoMale.Text : rdoFemale.Text;
55 // 提交学员信息
56 string message = studentManager.AddStudent(student);
57 MessageBox.Show(message, "提交提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
58
59 }
60
61 业务逻辑层
62 //对实体类对象分析,判断。将有效数据对象传入数据访问层
63 public string AddStudent(Student student)
64 {
65 //返回信息
66 string message = string.Empty;
67 //学员ID
68 int studentID = 0;
69 studentID =
studentService.GetStudentIDByLoginID(student.LoginId);
70 if(studentID>0)
71 message ="此学员用户名已存在,请更换后重新创建!";
72 else
73 {
74 studentID = studentService.AddSutdent(student);
75 if (studentID > 0)
76 message = "学员账户创建成功!";
77 else
78 message = "学员账户创建失败!";
79 }
80 return message;
81 }


82
83 数据访问层
84 //对实体类对象分析提取参数值 执行SQL
85 public int AddSutdent(Student student)
86 {
87 int number;
88 using (SqlConnection conn = new SqlConnection(connString))
89 {
90 SqlCommand objCommand = new SqlCommand(dboOwner +
".usp_InsertPartStudentInfo", conn);
91 objCommand.CommandType = CommandType.StoredProcedure;
92
93 objCommand.Parameters.Add
("@LoginID", SqlDbType.NVarChar, 50).Value = student.LoginId;
94 objCommand.Parameters.Add
("@LoginPwd", SqlDbType.NVarChar, 50).Value = student.LingPwd;
95 objCommand.Parameters.Add
("@UserStateId", SqlDbType.Int).Value = student.UserStateId;
96 objCommand.Parameters.Add
("@ClassID", SqlDbType.Int).Value = student.ClassID;
97 objCommand.Parameters.Add
("@StudentNO", SqlDbType.NVarChar, 255).Value = student.StudentNO;
98 objCommand.Parameters.Add
("@StudentName", SqlDbType.NVarChar, 255).Value = student.StudentName;
99 objCommand.Parameters.Add
("@Sex", SqlDbType.NVarChar, 255).Value = student.Sex;
100 conn.Open();
101 number = Convert.ToInt32(objCommand.ExecuteScalar());


102 conn.Close();
103
104 }
105 return number;
106 }
107
108






/////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////

1 public IList<Student> GetAllStudents()
2 {
3 IList<Student> students = new List<Student>();
4 using (SqlConnection conn = new SqlConnection(connString))
5 {
6 SqlCommand objCommand =
new SqlCommand(dboOwner + ".usp_SelectStudentsAll", conn);
7 objCommand.CommandType = CommandType.StoredProcedure;
8 conn.Open();
9 using (SqlDataReader objReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection))
10 {
11 while (objReader.Read())
12 {
13 Student student = new Student();
14 student.LoginId =
Convert.ToString(objReader["LoginId"]);
15 student.StudentNO =
Convert.ToString(objReader["StudentNO"]);
16 student.StudentName =
Convert.ToString(objReader["StudentName"]);


17 student.Sex =
Convert.ToString(objReader["Sex"]);
18 student.StudentIDNO =
Convert.ToString(objReader["StudentIDNO"]);
19 student.Phone =
Convert.ToString(objReader["Phone"]);
20 students.Add(student);
21 }
22 }
23 conn.Close();
24 conn.Dispose();
25 }
26 return students;

27 }

[其他解释]
恳请高手指点一下^_^
[其他解释]
最近在数据集,实体类设计的问题上迷路了……
[其他解释]
顶一下
[其他解释]
http://hi.baidu.com/beyondsmj/blog/item/1cd2910a7dc1351f94ca6b11.html
[其他解释]
去看看就更清楚了

[其他解释]
再顶一下!
[其他解释]
楼主,我和你的代码不会这么像吧????

using System;
using System.Collections.Generic;
using System.Data.Common;
using Forever.Source.Schema;

namespace Forever.Source.Entity
{
public interface ITableEntity<T>
{
#region 系 统 执 行


TableInfo TableInfo { get; set; }

#endregion


#region 留 给 子 类 的 继 承

T GetEntity(ValueDictionary values, bool exceptionSql);

T NewEntity();



List<T> GetList(bool exceptionSql);
List<T> GetList(ValueDictionary wheres, bool exceptionSql);
List<T> PageList(int page, int size, ref int count, bool exceptionSql);
List<T> PageList(int page, int size, ref int count, ValueDictionary wheres, bool exceptionSql);
int Delete(ValueDictionary wheres, bool exceptionSql);
int Delete(bool exceptionSql);
int Delete(T t);
int Insert(ValueDictionary values, bool exceptionSql);



string SqlOrder { get; set; }
string SqlGroup { get; set; }

#endregion


#region 在 ResultCollection 取值

/// <summary>
/// 用于保存实际需要数据的 字典;该属性为 每个对象一个;
/// </summary>
ValueDictionary CustomerValueInfos { get; set; }
/// <summary>
/// 当当前对象作为查询条件时,所保存的查询数据;
/// </summary>
ValueDictionary CustomerWhereInfos { get; set; }
/// <summary>
/// 保存 Order By 和 Group By 等的字典
/// </summary>
ValueDictionary CustomerExtendInfos { get; set; }

/// <summary>
/// 清空当前对象保存的所有查询条件
/// </summary>
void ClearWhere();

/// <summary>
/// 设置属性,该函数会通过当前 对象的身份,将数据保存到 CustomerValueInfos 或 CustomerWhereInfos;
/// </summary>
void SetProperty(string key, object value);

int ResultInt(string key);
double ResultDouble(string key);
float ResultFloat(string key);
string ResultString(string key);
DateTime ResultDateTime(string key);
Guid ResultGuid(string key);
byte[] ResultBytes(string key);


bool ResultBoolean(string key);
long ResultLong(string key);
char ResultChar(string key);

#endregion




T ReadEntityHandler(DbDataReader reader);


}
}



#region  其 他 的 函 数

public virtual T ReadEntityHandler(DbDataReader reader)
{
T entity = NewEntity();
ITableEntity<T> t = (ITableEntity<T>)entity;

ColumnCollection list = TableInfo.Columns;
foreach (ColumnInfo colomn in list.Values)
{
object obj = reader[colomn.SqlAlias];
if (obj != null && obj != DBNull.Value)
{
try
{
if (colomn.Type == typeof (int))
t.CustomerValueInfos.AddResult(colomn.Name, (int) obj);
else if (colomn.Type == typeof (double))
t.CustomerValueInfos.AddResult(colomn.Name, (double) obj);
else if (colomn.Type == typeof (float))
t.CustomerValueInfos.AddResult(colomn.Name, (float) obj);
else if (colomn.Type == typeof (string))
t.CustomerValueInfos.AddResult(colomn.Name, (string) obj);
else if (colomn.Type == typeof (DateTime))


t.CustomerValueInfos.AddResult(colomn.Name, (DateTime) obj);
else if (colomn.Type == typeof (Guid))
t.CustomerValueInfos.AddResult(colomn.Name, (Guid) obj);
else if (colomn.Type == typeof (byte[]))
t.CustomerValueInfos.AddResult(colomn.Name, (byte[]) obj);
else if (colomn.Type == typeof (bool))
t.CustomerValueInfos.AddResult(colomn.Name, (bool) obj);
else if (colomn.Type == typeof (char))
t.CustomerValueInfos.AddResult(colomn.Name, (char) obj);
else if (colomn.Type == typeof (decimal))
t.CustomerValueInfos.AddResult(colomn.Name, (decimal) obj);
else
t.CustomerValueInfos.AddResult(colomn.Name, obj);
}
catch (Exception ex)
{
string message = string.Format("Forever.ReadEntity 读取对象出现未知错误,如果无法解决,请改写 ReadEntity 函数!\r\n 微软的异常{0}\r\n当前字段{1}\r\n转换类型{2}", ex.Message, colomn.SqlAlias, colomn.Type.Name);
string logStr = string.Format("ReadEntity 函数错误!\r\n 微软的异常{0}\r\n当前字段{1}\r\n转换类型{2}", ex.Message, colomn.SqlAlias, colomn.Type.Name);
throw new Exception(message);


}
}

}
return entity;
}




public virtual T NewEntity()
{
return (T)Activator.CreateInstance(typeof(T));
}


读书人网 >.NET

热点推荐