我有实体对象,例如:从 EF 自动生成的文章。如果我将按照以下方式创建模型(用于创建、编辑实体对象):
public class ArticleModel
{
// properties
}
在创建、编辑操作中,我将从模型中设置实体的每个属性。通常,我使用以下类从模型到实体自动设置属性,并从实体到模型自动加载属性:
public interface IEntityModel<TEntity> where TEntity : EntityObject
{
void LoadEntity(TEntity t);
TEntity UpdateEntity(TEntity t);
TEntity CreateEntity();
}
public class EntityModel<TEntity> : IEntityModel<TEntity> where TEntity : EntityObject
{
public virtual void LoadEntity(TEntity t)
{
var entityType = typeof(TEntity);
var thisType = this.GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
PropertyInfo[] thisProperties = thisType.GetProperties();
PropertyInfo temp = null;
lock (this)
{
thisProperties.AsParallel()
.ForAll((p) =>
{
if ((temp = entityProperties.SingleOrDefault(a => a.Name == p.Name)) != null)
p.SetValue(this, temp.GetValue(t, null), null);
});
}
}
public virtual TEntity UpdateEntity(TEntity t)
{
var entityType = typeof(TEntity);
var thisType = this.GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
PropertyInfo[] thisProperties = thisType.GetProperties();
PropertyInfo temp = null;
lock (t)
{
entityProperties.AsParallel()
.ForAll((p) =>
{
if (p.Name.ToLower() != "id" && (temp = thisProperties.SingleOrDefault(a => a.Name == p.Name)) != null)
p.SetValue(t, temp.GetValue(this, null), null);
});
}
return t;
}
public virtual TEntity CreateEntity()
{
TEntity t = Activator.CreateInstance<TEntity>();
var entityType = typeof(TEntity);
var thisType = this.GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
PropertyInfo[] thisProperties = thisType.GetProperties();
PropertyInfo temp = null;
lock (t)
{
entityProperties.AsParallel()
.ForAll((p) =>
{
if (p.Name.ToLower() != "id" && (temp = thisProperties.SingleOrDefault(a => a.Name == p.Name)) != null)
p.SetValue(t, temp.GetValue(this, null), null);
});
}
return t;
}
}
这样,如果模型是从 EntityModel 继承的并且属性名称与实体属性匹配,则在创建和编辑操作中我可以编写:
// for create entity
Article a = model.CreateEntity();
// for update entity
a = model.UpdateEntity(a);
// for load from entity
model.LoadEntity(a);
我知道我的班级弱点。例如,如果某些属性未从视图中编辑,则在 UpdateEntity() 方法中,实体的旧值将被删除。
问题:是否存在我不知道的另一种方式或常见方式?