5

我正在使用EF 4.2代碼優先模型的項目。該模型包含產品的TPH繼承結構。我需要將這個繼承模型的多態結果在鑑別器上分組,並且遇到一些問題。實體框架4.2每個層次結構組按辨別器

實體框架不公開鑑別符來完成這個分組。我的第一個問題是我可以直接訪問這個鑑別器嗎?我的閱讀和經驗告訴我不,所以我想出了這種解決方案。它表現不佳,我不滿意它將如何維護。

我的課是這個樣子(簡化):

Public MustInherit Class Product 
     <key()> 
     Public Property ProductID as integer 

     <StringLength(50, ErrorMessage:="Max 50 characters")> 
     <Required(ErrorMessage:="Product name is required")> 
     Public Property Name as String 

     <TimeStamp()> 
     Public Property Time_Stamp as DateTime = DateTime.Now() 
End Class 

Public Class Desktop 
     Inherits Product 

     <StringLength(50, ErrorMessage:="Max 50 characters")> 
     <Required(ErrorMessage:="Processor is required")> 
     Public Property Processor as String 
End Class 

Public Class Monitor 
     Inherits Product 

     <Required(ErrorMessage:="Monitor size is required")> 
     Public Property Size_Inches as Integer 
End Class 

我建立,需要一個產品,並返回它的基本類型名稱爲字符串的擴展方法。

<Extension()> 
Public Function ProductType(ByVal inProduct as Product) as String 
     ProductType = inProduct.GetType().BaseType.Name 
End Function 

就這樣,我建立了這個結構,集團產品的結果,按類型,所以我可以貫穿其中:

Dim tmpProducts = db.Products.ToList() 
Dim GrpProducts = tmpProducts.GroupBy(Function(prod) prod.ProductType) _ 
          .Select(Function(s) New With {.ProductType = S.Key, 
                  .Products = S }) 

我現在可以循環通過列表來獲得我想要的行爲,但表現並不理想,而且我擔心隨着產品數量的增長,這將是不可接受的。

For Each ProductGroup in GrpProducts 
     Dim TypeName as String = ProductGroup.ProductType 
     Dim TypeProducts = ProductGroup.Products 
Next 

此外,這可以給我輕鬆訪問共享屬性(名稱),但現在我沒有很多選擇,這些投到他們真正的類型,也許周圍的TypeName一個選擇的情況下。 。 。

任何建議表示讚賞,也請原諒上面的任何代碼錯誤,我重新從內存中的例子,因爲我目前無法訪問該項目。

回答

2

一個解決方案是建立一個更多的模型,並有一個新的實體ProductType有一個屬性Name。那麼你將在ProductProductType之間有一個簡單的1-N關係。我沒有使用EntityFramework,但是使用NHibernate,您可以很容易地讓框架始終在查詢中加入該表,以便它不會爲每個Product返回代理ProductType,這可能會損害性能。

作爲一個附加的,在未來ProductType可以發展其他有趣的特性(比如是該ProductType的每Product共同價值觀),所以它增加了靈活性,以您的解決方案,雖然它確實有直接成本將另一個表添加到您的數據庫。

+0

這當然是一個選項,以解決組,雖然我覺得共同財產屬於該類型定義可能的情況下。最近我一直在向基類添加一個可覆蓋的「ProductTypeName」屬性。感覺到cludgy並重復存儲的數據,但它確實表現更好。 – sgrade1979

1

繼Linq查詢應該讓你的方式通過鑑別

from a in db.Records 
group a.ID by new 
{ 
    Name= a is Audio ? "Audio" : 
      a is Video ? "Video" : 
      a is Picture ? "Picture" : 
      a is Document ? "Document" : "File" 
} into g 
select new 
{ 
    Name = g.Key.Name, 
    Total = g.Count() 
} 
相關問題