将属性实体映射到父实体上的列

时间:2014-07-29 20:37:51

标签: c# entity-framework

我们说我有两个简单的类:

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来映射' Price'只要遇到它就会列到列。

1 个答案:

答案 0 :(得分:1)

我不确定完全正确的符号,但这是我所知道的最简单,最易维护的方式。 (我已经在下面提到了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

相关问题