在部分类中添加属性后,EF核心“字段列表中的未知列”

I have a DB-first EF core model OrderableItem with a helper property added in its partial part:

public partial class OrderableItem {

  public decimal EffectivePrice {
    get => IsSpecial ? Special.Price : Price;
    set {
      if (IsSpecial)
        Special.Price = value;
      else 
        Price = value;
    }
  }
}

但是,添加此属性后,我将无法再查询DbSet(MySql提供程序),并引发异常:

MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'i.EffectivePrice' in 'field list'

尽管很明显,但它并没有说明EF为什么要查询模型中未定义(并且不应该!)的属性。如何解决此问题?我是否限于局部分析方法?

评论
  • beos
    beos 回复

    You should specify properties which should be ignored by DbContext using modelBuilder's method ignore. builder.Entity<OrderableItem>().Ignore(x => x.EffectivePrice).
    You can achieve same using attributes but if your class is used as domain entity then it should not contain any infrastructure dependencies.

  • Tim
    Tim 回复

    By default, EF Core would try to map all the properties as long as they have both getter and setter. If you need to ignore a specific property, you can use NotMapped attribute:

    public partial class OrderableItem {
    
      [NotMapped]
      public decimal EffectivePrice {
        get => IsSpecial ? Special.Price : Price;
        set {
          if (IsSpecial)
            Special.Price = value;
          else 
            Price = value;
        }
      }
    }