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()方法中刪除實體舊值。
問題:是否存在另一種我不知道的方式或常用方式?