我正在使用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一個選擇的情況下。 。 。
任何建議表示讚賞,也請原諒上面的任何代碼錯誤,我重新從內存中的例子,因爲我目前無法訪問該項目。
這當然是一個選項,以解決組,雖然我覺得共同財產屬於該類型定義可能的情況下。最近我一直在向基類添加一個可覆蓋的「ProductTypeName」屬性。感覺到cludgy並重復存儲的數據,但它確實表現更好。 – sgrade1979