2011-12-06 45 views
1

在id和對象之間映射的最佳方式是什麼?對於示例具有OrderItemPreference類,該類具有屬性PreferenceId <的ID和首選項。我希望首選項能夠從緩存中讀取數據庫中的數據。從字典中獲取首選項object.Like preferencesDictionary [id]。爲每個項目查詢數據庫的速度都很慢。因爲每個產品都有3-4個首選項,每個項目都指向一個組,所以數據太多。再次寫入相同的映射代碼看起來很糟糕。爲POCO實現簡單緩存

我不能和我不想使用ORM。

最簡單的解決方案是在POCO的屬性中嵌入從緩存中讀取的代碼。但這對我來說似乎不正確。任何解決方案如何實現?

回答

3

假設您正在使用的存儲庫模式(你沒有,但這個想法是對其他數據訪問模式類似):

interface IPocoRepository { 
    Poco GetById(int id); 
} 

class DatabasePocoRepository : IPocoRepository { 
    public Poco GetById(int id) { 
     // read the POCO from the database 
    } 
} 

class CachePocoRepository : IPocoRepository { 
    private readonly IPocoRepository pocoRepository; 
    public PocoCachingRepository(IPocoRepository pocoRepository) { 
     this.pocoRepositry = pocoRepository; 
    } 

    public Poco GetById(int id) { 
     // read from the cache 
     // if available, return it 
     // if not, load using pocoRepository and cache 
    } 
} 

現在的任何地方,你需要一個PocoRepository和希望啓用緩存,請使用CachingPocoRepository。顯然你需要編寫緩存策略。

+0

謝謝你的模式,但我的問題是如何調用它。我想調用Order.Table <和Table來例如使用Order.TableId從緩存中返回Table對象。我應該在哪裏放這個代碼?把它放在物業內(表)是好事嗎? 。要在代碼中手動加載它會增加複雜性。就像在一個循環中構建一個報告,如果我在那裏添加代碼來檢查每個項目是否被加載,這會使代碼太複雜.. – GorillaApe

+0

整體來說,緩存與POCO對象的性質沒有密切關係。它與數據訪問密切相關,這就是代碼應該在的地方:在數據訪問代碼中,並在數據訪問層使用。 – jason

+0

所以我應該把它放到我的DAO代碼中,我加載數據?這似乎更好。 – GorillaApe