0

存儲庫模式中有點新東西。試圖構建一個通用的存儲庫,該存儲庫還將處理派生實體的狀態更改。到目前爲止,我所做的是創建一個自定義屬性,將屬性標記爲需要插入的屬性。使用反射來在通用資源庫中插入派生實體

屬性:

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類)。

回答

0

您可以使用pi.GetValue(entity, null)獲得值,併爲屬性類型創建通用存儲庫(Activate.CreateInstance) (來自pi),但是你必須做很多反思。

在這種情況下,您應該考慮刪除經典通用存儲庫的想法(每個類型單獨存儲庫)並使用類似擴展的DbContext之類的可處理所有類型的東西。

如果您有斷開連接的情況(WCF),主要問題將是EF本身,因爲您必須將所有更改複製到服務器端的嵌套列表並手動更改EntityState。

+0

感謝您的回覆科斯。你是對的,太多的反思,以優雅的方式來解決這個問題。代碼變得混亂了,我爲更復雜的實體創建了服務。 (抱歉,延遲的答覆,BTW) – kmunky