我有实体对象,例如:从EF自动生成的文章。如果我要创建模型(用于创建,编辑实体对象),请采用以下方式:
public class ArticleModel
{
// properties
}在Create,Edit操作中,我将从模型中设置实体的每个属性。通常,我将以下类用于从一个模型到另一个实体的自动设置属性和从一个实体到另一个模型的自动加载属性:
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()方法中,实体的旧值将被删除。
问题:我不知道是否存在另一种方式或常见的方式?
发布于 2012-08-16 10:36:42
基本上,您是自己编写整个。MVC可以直接做到这一点。控制器有一个名为UpdateModel的方法,用于更新模型。
可以找到这里、这里和这里的例子。关于它是如何工作的更多信息,这里。
https://stackoverflow.com/questions/11985221
复制相似问题