怎样给表的实体类赋值??
因为我是根据一个库随机动态的获取表的表名,所以表的结构也是动态的,这样我怎样给获取的表添加一条数据呢??
[解决办法]
利用反射
[解决办法]
public IEntity GetEntity(IEntity entity)//目前只能根据ID查询 { try { Type type = entity.GetType(); PropertyInfo[] list = type.GetProperties(); string sql = "select top 1 * from " + type.Name + " where "; foreach (PropertyInfo info in list) { if (info.Name == GetKeyName(type.Name)) { sql += info.Name + "=" + info.GetValue(entity, null); break; } } DataTable dt = Query(sql); if (dt.Rows.Count > 0) { for (int j = 0; j < list.Length; j++) { if (list[j].Name == GetKeyName(type.Name) || dt.Rows[0][list[j].Name] is DBNull) { continue; } string columnName = list[j].Name; object value = dt.Rows[0][columnName]; list[j].SetValue(entity, value, null); } return entity; } else { return null; } } catch (Exception ex) { throw new Exception(ex.Message); } }
[解决办法]
{
foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
{
try
{
int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
}
}
catch
{
break;
}
}
}
lst.Add(RowInstance);
}
return lst;
}