【问题标题】:Make a reference to a field of a foreign key in model引用模型中的外键字段
【发布时间】:2020-05-23 16:31:42
【问题描述】:

我有以下型号:

public class Item {
   public string ItemID {get; set;}

   public decimal AvailableQuantity {get; set;}
}

public class Element {
   public string ElementID {get; set;}

   [ForeignKey("Item")]
   public string ItemID { get; set; }
   public virtual Item Item { get; set; }

   public decimal Quantity {get; set;}
}

我希望 Element 中的 Quantity 字段始终小于它所代表的 Item。我尝试使用万无一失的数据注释:

[Foolproof.LessThanOrEqualTo(Item.AvailableQuantity)]
public decimal Quantity { get; set; }

但我收到以下错误:

CS0120: An object reference is required for the non-static field, method, or property 'Element.Item'

我能做些什么来满足这个条件?我想用它来验证表单中的数据。

【问题讨论】:

    标签: asp.net-mvc entity-framework model


    【解决方案1】:

    我认为你还有另一个问题:

    public class Item {
       public string ItemID {get; set;}
    
       public decimal AvailableQuantity {get; set;}
    }
    
    public class Element {
       public string ElementID {get; set;}
    
       [ForeignKey("Item")] // you dont have a property called Item here except from the Item 
        object which cant be used as a foreign key.
       public string ItemID { get; set; }
       [ForeignKey("ItemID")] //this will work
       public virtual Item Item { get; set; }
    
       public decimal Quantity {get; set;}
    }
    

    至于数据注释 Foolproof 有选项,但我认为你不能在这些模型上做到这一点。 尝试创建一个 ViewModel,以便比较的属性在同一个模型中; 这可能有效:

    [GreaterThan("Quantity")]
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 2016-04-30
      • 2017-10-04
      • 2015-06-13
      • 2020-06-30
      • 2021-09-13
      相关资源
      最近更新 更多