2012-08-16 36 views
0

我有实体对象,例如:从EF自动生成的文章。如果我将创建模型(用于创建,编辑实体对象)方式如下:集成它的EntityObject和EntityModel它的

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()方法中删除实体旧值。

问题:是否存在另一种我不知道的方式或常用方式?

回答

0

基本上,您自己正在编写整个更新模型与更改从发布网页。 MVC可以开箱即用。控制器有一个名为UpdateModel的方法,它可以更新模型。

可以找到例子here,herehere。更多关于它如何工作的信息,here