1

目前我有一個項目需要處理帶有用戶可以指定的自定義字段的產品。使用實體框架處理自定義字段

有沒有人知道什麼是使用模型和代碼第一批註實現這個最好的方法?

我想到了數據庫端,我將需要一個新表來處理將鏈接到productID的自定義數據。

回答

3

您可以爲用戶可以添加的自定義屬性指定一個單獨的表。此自定義字段將對您的主要模型有一個參考。基本上,你將有1 to M關係

public class MyModel 
{ 
    public int MyModelID   { get; set; } 

    public string FixedProperty1 { get; set; } 
    public string FixedProperty2 { get; set; } 

    // This is a navigation property for all your custom properties 
    public virtual ICollection<CustomProperty> CustomProperties { get; set; } 
} 

public class CustomProperty 
{ 
    public int CustomPropertyID  { get; set; } 

    // This is the name of custom field 
    public string PropertyName  { get; set; } 
    // And this is its value 
    public string PropertyValue  { get; set; } 

    // FK reference and navigation property to your main table 
    public int MyModelID    { get; set; } 
    public virtual MyModel MyModel { get; set; } 
} 
+0

將它指定爲「虛擬」功能的目的是什麼? – ChaoticLoki

+1

虛擬在EF上下文中具有不同的含義。它提供了延遲加載。基本上,當你從數據庫獲取MyModel時,除非明確請求它,否則它不會爲它帶來自定義屬性。如果您確信大部分時間您都需要模型本身的自定義屬性,則可以安全地移除虛擬關鍵字。更多信息在這裏。 http://stackoverflow.com/questions/5597760/what-effects-can-the-virtual-keyword-have-in-entity-framework-4-1-poco-code-fi –

+0

哦好吧,我知道關於懶加載根據我對教條的經驗,我沒有意識到使用'虛擬'是你如何處理EF的。非常感謝您的信息! – ChaoticLoki