存儲庫模式中有點新東西。試圖構建一個通用的存儲庫,該存儲庫還將處理派生實體的狀態更改。到目前爲止,我所做的是創建一個自定義屬性,將屬性標記爲需要插入的屬性。使用反射來在通用資源庫中插入派生實體
屬性:
public class DerivedObjectAttribute : Attribute
{
public enum EntityType
{
REFERENCE,
OBJECT
}
public EntityType DerivedType { get; set; }
}
我定義上,我想級聯狀態變化的任何屬性此屬性。
樣品實體:
public class FightingCharacter : BaseEntity
{
public Costume costume { get; set; }
[DerivedObject(DerivedType=DerivedObjectAttribute.EntityType.REFERENCE)]
public SpecialFinish specialFinish { get; set; }
[DerivedObject(DerivedType = DerivedObjectAttribute.EntityType.REFERENCE)]
public List<MoveList> moveList { get; set; }
}
因此,對於這個類,服裝屬性就不需要級聯,但specialFinish和moveList性能應。
然後在我的倉庫:
public class DataRepository<T> : IRepository<T> where T : BaseEntity {
private void TryDerivedUpsert(T entity)
{
Type type = entity.GetType();
PropertyInfo[] piList = type.GetProperties();
foreach (PropertyInfo pi in piList)
{
foreach (DerivedObjectAttribute attr in pi.GetCustomAttributes(typeof(DerivedObjectAttribute), false))
{
// What to do here?
}
}
}
}
最內層循環中,我能夠查明DerivedObjectAttributes沒有任何問題。問題是:如何獲取對象的類型和值,然後插入它?換句話說:如果屬性pi被標記爲級聯更改,請創建一個到相應實體的回購,並將其上移。 E.G .:
DataRepository<EntityType> repo = new DataRepository<EntityType>();
repo.Upsert(property as EntityType);
這是否有意義?或者我完全用錯誤的方式去了解通用回購?如果它是有道理的(我會感到驚訝),如何做到這一點? (這裏列出的例子僅僅是示例,BTW,我仍然在架構中,並且還沒有EF類)。
感謝您的回覆科斯。你是對的,太多的反思,以優雅的方式來解決這個問題。代碼變得混亂了,我爲更復雜的實體創建了服務。 (抱歉,延遲的答覆,BTW) – kmunky