我有实体对象,例如:自动从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()方法中将删除实体的旧值。
问题:是否存在我不知道的其他方式或常用方式?