【问题标题】:RavenDB - Computed PropertiesRavenDB - 计算属性
【发布时间】:2014-09-07 05:47:07
【问题描述】:

我有一个包含一些计算属性的文档。没有setter并且可以在我的类上调用其他方法来返回结果的属性,例如:

public class Order
{
    public string CustomerId { get; set; }

    public string VehicleId { get; set; }

    public DateTime OrderDate { get; set; }

    public decimal CommissionPercent { get; set; }

    public List<OrdersLines> OrderLines { get; set; }

    public decimal Total
    {
        get { return GetOrderLinesTotal() + SomeDecimal + AnotherDecimal; }
    }

    public decimal GetOrderLinesTotal()
    {
        return OrderLines.Sum(x => x.Amount);
    }
}

我使用一个简单的索引来按客户、日期和 Vehicle 文档上的某些属性搜索订单,使用 lucene 查询和 Transformer 来创建我的视图模型。我查看了脚本索引结果,但不确定它是否适用于这种情况。

public class ViewModel
{
    public string OrderId { get; set; }
    public string CustomerName { get; set; }
    public string VehicleName { get; set; }
    public string Total { get; set; }
}

当我查询这些文档时,如何从 Total 属性中获取计算值?

我对 GetOrderLinesTotal 做了一些简化,实际上它是一个复杂的方法,在计算总数时会考虑很多其他属性。

我只得到在文档创建或更新时序列化的计算值。

【问题讨论】:

    标签: ravendb


    【解决方案1】:

    我意识到这更像是一个文档设计问题,而不是尝试做一些 RavenDB 不打算做的事情。我简化了我的文档并使用了 map/reduce 来解决问题。

    【讨论】:

      【解决方案2】:

      我认为您的情况类似于我曾经遇到的问题。我在我的公共 get 属性上使用JsonIgnore 属性并使用私有支持字段,我使用JsonProperty 属性将其包含在序列化中。您应该能够应用类似的想法:

      /// <summary>
      /// The <see cref="Team" /> class.
      /// </summary>
      public class Team
      {
          /// <summary>
          /// The ids of the users in the team.
          /// </summary>
          [JsonProperty(PropertyName = "UserIds")]
          private ICollection<string> userIds;
      
          // ...[snip]...
      
          /// <summary>
          /// Gets the ids of the users in the team.
          /// </summary>
          /// <value>
          /// The ids of the users in the team.
          /// </value>
          [JsonIgnore]
          public IEnumerable<string> UserIds
          {
              get { return this.userIds; }
          }
      
          // ...[snip]...
      } 
      

      【讨论】:

      • 我认为这与我遇到的问题不同。我的问题是属性 Total 是一个计算属性,它在我的类上调用另一个方法。由于我按类使用 Transformer,因此永远不会实例化,也不会返回正确的计算值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2013-06-29
      • 2020-02-03
      • 2020-07-19
      相关资源
      最近更新 更多