簡體   English   中英

實體框架流利的api如何有條件地將多個屬性映射到單個表

[英]Entity Framework fluent api how to conditionally map multiple properties to a single table

使用fluent api,如何將相同數據類型的多個屬性有條件地映射到單個表。

數據庫模型: 數據庫模型

  • ListType將包括分組名稱,即過敏原
  • ListItem將包含給定類型的所有可能值
  • ProductListItem包含給定產品的所有“選定”值。

目標是使用ProductListItem表,並將其應用於基於ListType(WHERE ProductListItem.ListTypeID = 1)的模型(具有相同ProductListItem類型)的多個屬性中。

public class Product
{
    public int ProductID { get; set; }
    public List<ProductListItem> Allergens { get; set; }
    public List<ProductListItem> DoesNotContain { get; set; }
}

我真的不認為可以通過條件映射來實現這一目標,但可以作弊。

 public List<ProductListItem> Allergens 
 { 
    get { return this.ProductListItems.Where(i => i.ListType.Name=="Allergens").ToList=();}
 }

或者,您可以選擇為具有相同基類的不同ListItem創建單個類,並使用TPH映射: http : //weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first- ctp5-part-1-table-per-hierarchy-tph

該代碼將是這樣的:

class Product
{
  public List<AllergenProductListItem> Allergens { get; set; }
  public List<DoesNotContainListItem> DoesNotContain { get; set; }
}

對於項目類型的數量,它顯然不是動態的(很難添加新的類型),但是您也不希望得到解決方案,因為如果您要使用新的類型,則應該修改代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM