簡體   English   中英

將屬性實體映射到父實體上的列

[英]Map property entity to column(s) on parent entity

假設我有兩個簡單的類:

public class Product
{
    public int Id { get; set; }
    public string Description { get; set; }
    public Price Price { get; set; }
}

public class Price
{
    public decimal Amount { get; set; }
    public string Currency { get; set;
}

注意產品價格是Price一個實例。

現在:我想使用Entity Framework(代碼優先)將Product實例存儲在名為“ Products”的表中,但我也希望將Price屬性簡單地存儲為字符串,即“ 100USD”或十進制和字符串列。

默認情況下,EF還將嘗試創建“價格”表,但抱怨主鍵沒有可用的屬性。

有辦法解決這個問題嗎?

同樣重要的是,我不必在模型中添加“ cruft”,即可以容納EF的其他方法或屬性。 理想情況下,我只需要配置EF,以便在遇到“價格”類的實例時將其映射到列。

我不確定確切的表達方式是什么,但這是我所知道的最簡單,最可維護的方法。 (我在下面包括了marc_s的評論/建議)。

public class Product
{
  public Product()
  {
    this.Price = new Price();
  }

  public int Id { get; set; }
  public string Description { get; set; }

  [NotMapped]
  public Price Price { get; set; }

  [Column("Price")]
  public string RawPrice 
  {
    get
    {
      return this.Price.<yourfield>;  
    }
    set
    {
      this.Price.SetRawValue(value);
    }
  }

  [Column("Currency")]
  public string RawCurrency
  {
    get
    {
      return this.Price.<yourfield>;  
    }
    set
    {
      this.Price.SetRawCurrency(value);
    }
  }
}

public class Price
{
  public decimal Amount { get; set; }
  public string Currency { get; set;
  public void SetRawPrice(string value)
  {
    //parse raw value into amount
  }
  public void SetRawCurrency(string value)
  {
    //parse raw value into currency
  }
}

這可能會或可能不會,我無法測試:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
  base.OnModelCreating(modelBuilder);

  modelBuilder.ComplexType<Price>();
  modelBuilder.Entity<Product>()
    .Property(p => p.Price.Amount)
    .HasColumnName("Amount");
  modelBuilder.Entity<Product>()
    .Property(p => p.Price.Currency)
    .HasColumnName("Currency");
}

我認為這是為了使模型扁平化,但我從未做過。 YMMV

暫無
暫無

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

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