标签:
public class IdName { public Guid Id { get; set; } public string Name { get; set; } }
(一)新建一个idName类放在model类库里面,定义两个自动属性。
public class IdNameDAL
{
public IdName[] GetByCategory(string category)
{
DataTable table = SqlHelper.ExecuteDataTable("select Id,Name from T_IdName where Category=@Category",
new SqlParameter("@Category", category));
IdName[] items = new IdName[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
IdName idname = new IdName();
idname.Id = (Guid)row["Id"];
idname.Name = (string)row["Name"];
items[i] = idname;
}
return items;
}
首先根据参数取出来一个DataTable类的一张数据表(很多行和列),取出每一个行(table.row[i]),放入DataRow中,声明一个类用来装取出来的每个列值(row【“列名”】),把每一行都放入一个类(装一行),再把这每个类放入一个类数组(装的是一个表)中返回。
(二)声明一个operator类放入Model类库中,定义好字段
public class Operator { public Guid Id { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool IsDeleted { get; set; } public string RealName { get; set; } public bool IsLocked { get; set; } }
public Operator[] ListAll() { DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Operator where IsDeleted=0"); Operator[] operators = new Operator[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { operators[i] = ToOperator(dt.Rows[i]); } return operators; } private Operator ToOperator(DataRow row) { Operator op = new Operator(); op.Id = (Guid)row["Id"]; op.UserName = (string)row["UserName"]; op.Password = (string)row["Password"]; op.IsDeleted = (bool)row["IsDeleted"]; op.RealName = (string)row["RealName"]; op.IsLocked = (bool)row["IsLocked"]; return op; }
这个函数返回数据库的一张表的全部信息。首先定义一个函数,输入一个datarow类型的参数(表中的一行),把其中的每个列放入都放入一个类所对应的字段,返回这个类。严谨的应该加一个判断,若是dbnull.value
就返回null。
c#数据类型 | sql server数据类型 |
uniquerteidentifier newid() | guid |
bool | bit |
decimal | mony |
public IEnumerable<Department> ListAll() { List<Department> list = new List<Department>(); DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Department where IsStopped=0"); foreach (DataRow row in dt.Rows) { Department dept = ToModel(row); list.Add(dept); } return list; }
private Department ToModel(DataRow row)
{
Department dept = new Department();
dept.Id = (Guid)SqlHelper.FromDbValue(row["Id"]);
dept.Name = (string)SqlHelper.FromDbValue(row["Name"]);
return dept;
}
这个函数使用list<类>集合写的,和前面的数组同样的效果,取出行放入集合类中,用数组的都可以用集合代替,显得高大上返回之用IEnumerable<>是list《》泛型集合的父类。返回值给了父类。利用软删除(假删除)isdeleted=0或者=1;
标签:
原文地址:http://www.cnblogs.com/dandandeyoushangnan/p/4504727.html