很多人现在对于使用表(datatable)还是用实体很纠结,本人设计了一个模型,让实体指向表的一行,实体与表就统一了,示例如下
首先定义一个全局通用的类
#region 实体基类
/// <summary>
/// 通用的实体表
/// </summary>
public class tEntity<T> : IDisposable where T : EntityBase
{
public DataTable DataSouce { get; set; }
public tEntity(DataTable p_DataSouce)
{
if (p_DataSouce == null) throw new Exception("实体对应的表不能为空");
if (string.IsNullOrEmpty(p_DataSouce.TableName)) p_DataSouce.TableName = "Table_Name";
DataSouce = p_DataSouce;
}
public T this[int index]
{
get
{
T en = Activator.CreateInstance<T>();
en.CurrentRow = DataSouce.DefaultView[index].Row;
return en;
}
}
public int Count
{
get { return DataSouce.DefaultView.Count; }
}
/// <summary>
/// 新增实体
/// 若视图有过滤,必须设置初始值在当前过滤的条件内
/// </summary>
/// <returns></returns>
public T AddNew()
{
T en = Activator.CreateInstance<T>();
en.CurrentRow = DataSouce.NewRow();
DataSouce.Rows.Add(en.CurrentRow);
return en;
}
/// <summary>
/// 实体和表转换
/// </summary>
/// <returns></returns>
public T[] Entity
{
get
{
List<T> Entity = new List<T>();
for (int i = 0; i < DataSouce.Rows.Count; i++)
{
T en = Activator.CreateInstance<T>();
en.CurrentRow = DataSouce.DefaultView[i].Row;
Entity.Add(en);
}
return Entity.ToArray();
}
set
{
DataTable dt = value[0].CurrentRow.Table.Clone();
for (int i = 0; i < value.Length; i++)
{
dt.Rows.Add(value[i].CurrentRow.ItemArray);
}
dt.AcceptChanges();
DataSouce = dt;
}
}
public tEntity<T> Clone()
{
return new tEntity<T>(this.DataSouce.DefaultView.ToTable());
}
public void Dispose()
{
DataSouce.Dispose();
}
}
public abstract class EntityBase
{
public DataRow CurrentRow { get; set; }
public void Delete()
{
CurrentRow.Delete();
}
}
#endregion
每个真正的实体继承上面的类如:
public class Entity录入:EntityBase
{
public decimal? id
{
get
{
if (CurrentRow["id"] == DBNull.Value) return null;
return Convert.ToDecimal(CurrentRow["id"]);
}
set
{
CurrentRow["id"] = value;
}
//.......
}
public class tEntity录入 :tEntity<Entity录入>
{
public tEntity录入(DataTable p_DataSource) : base(p_DataSource) { }
}