这个知识没太看懂,现在利用这个平台记一下,非常好用,以后学的深入了自己理解一下!
需求:有一张表,要分别获取两列的字段,通过这些字段组成一个可以查询的SQL语句,这个要是在数据库端就好弄了,但是现在用C#代码集成,就有些困难
1.通过SQL语句获得一个datatable,例如:DataTable dt = _updateDb.DoQueryEx(querySql);
做过的人应该都知道什么意思,dt就是要利用c#代码来组成SQL语句的表
2.建立一个静态类
public static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
Type type = typeof(T);
List<T> list = new List<T>();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = type.GetProperties();
T entity = new T();
foreach (PropertyInfo myPropInfo in pArray)
{
string col_name = myPropInfo.Name;
try
{
if (row[col_name] is Int64)
{
myPropInfo.SetValue(entity, Convert.ToInt32(row[col_name]), null);
continue;
}
else if (row[myPropInfo.Name] is Int32)
{
myPropInfo.SetValue(entity, Convert.ToInt32(row[myPropInfo.Name]), null);
continue;
}
else if (row[myPropInfo.Name] is Decimal)
{
myPropInfo.SetValue(entity, Convert.ToInt32(row[myPropInfo.Name]), null);
continue;
}
else if (row[myPropInfo.Name] is String)
{
myPropInfo.SetValue(entity, Convert.ToString(row[myPropInfo.Name]), null);
continue;
}
else if (row[myPropInfo.Name] is Double)
{
myPropInfo.SetValue(entity, Convert.ToDouble(row[myPropInfo.Name]), null);
continue;
}
else if (row[myPropInfo.Name] is DateTime)
{
myPropInfo.SetValue(entity, Convert.ToDateTime(row[myPropInfo.Name]), null);
continue;
}
else
{
//nullable类型
if (myPropInfo.PropertyType.GetGenericTypeDefinition().Equals((typeof(Nullable<>))))
{
myPropInfo.SetValue(entity, Convert.IsDBNull(row[myPropInfo.Name]) ? null :
Convert.ChangeType(row[myPropInfo.Name], myPropInfo.PropertyType.GetGenericArguments()[0]), null);
}
else
{
myPropInfo.SetValue(entity, Convert.IsDBNull(row[myPropInfo.Name]) ? null : row[myPropInfo.Name], null);
}
break;
}
}
catch (Exception ex)
{ }
}
list.Add(entity);
}
return list;
}
3.根据dt来建立一个类,存储它,
public class Class_in
{
public class Class_IN
{
/// <summary>
/// 原表名字
/// </summary>
public string SPB_NM
{ set; get; }
/// <summary>
/// 原表字段
/// </summary>
public string SPZD_NM
{ set; get; }
/// <summary>
/// 更新表名字
/// </summary>
public string YB_NM
{ set; get; }
/// <summary>
/// 更新表字段
/// </summary>
public string YZD_NM
{ set; get; }
/// <summary>
/// 备注
/// </summary>
public string BZ
{ set; get; }
}
}
dt的表结构如下:
利用语句:
List<Class_IN> lstModel = EntityHelper.TableToEntity<Class_IN>(dt);
//EntityHelper是一个命名空间
将dt的每一条记录存到lstmodel中,
4. 利用,string basename = lstModel.Where(p => p.BZ != null && p.BZ.Contains("关联字段")).ToList().First().SPB_NM;
新建一个list,类型为Class_IN,这里就可以根据不同的条件设置来活的想要的一条记录,这里要说的是一个list的where方法的应用,
给一个链接:http://www.cnblogs.com/chunyih/p/3859453.html?utm_source=tuicool&utm_medium=referral
List<Class_IN> lst1 = lstModel.Where(p => p.SPB_NM == basename).ToList();