【问题标题】:How do I link a method to a property in MVC?如何将方法链接到 MVC 中的属性?
【发布时间】:2020-05-03 22:01:29
【问题描述】:

我正在学习 MVC,目前正在使用 MvcMusicStore 教程,但添加了一些附加功能和更多功能。

我有一种方法可以通过将数量乘以单价来计算总价。

我在模型中有一个名为TotalPrice 的属性,我希望将此方法“附加”到该属性上,以便TotalPrice 的值来自此方法。

方法名是GetTotal()

我的模型如下:

public class OrderDetail
{
    public int OrderDetailId { get; set; }
    public int OrderId { get; set; }
    public int AlbumId { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal TotalPrice { get; set; }


    public virtual Album Album { get; set; }
    public virtual Order Order { get; set; }

    MusicStoreEntities db = new MusicStoreEntities();
    public decimal GetTotal()
    {

        decimal? total = (from s in db.OrderDetails
                          where s.OrderDetailId == OrderDetailId
                          select (decimal?)Quantity * UnitPrice).Sum();
        return total ?? decimal.Zero;
    }
}

我希望方法返回的值填充TotalPrice 字段,当前为null,因为没有方法链接到它。

我怎样才能让TotalPriceGetTotal() 获得它的价值?

【问题讨论】:

    标签: c# asp.net-mvc model


    【解决方案1】:

    鉴于 TotalPrice 是一个属性,您可以从属性本身调用该方法:

    public decimal TotalPrice 
    { 
      get 
      { 
        return GetTotal();
      }
    }
    

    但是,当您应该能够使用模型中的数据时,我不建议您尝试从数据库中提取总价格,因此您应该这样做:

    public decimal TotalPrice 
    { 
      get 
      { 
        return Quantity * UnitPrice;
      }
    }
    

    如果您需要对订单中的所有项目求和,那么您需要在订单类中实现类似的内容:

    public class Order 
    { 
      List<OrderDetail> OrderDetails {get; set;}
      ....
    
    
      public decimal TotalPrice 
      { 
        get 
        {
          decimal total = 0;
          foreach (var o in OrderDetails) 
          {
            total += o.TotalPrice;
          }
          return total;
        }
    
      }
    }
    

    更新

    甚至更简单(需要导入 System.Linq):

    public class Order 
    { 
      List<OrderDetail> OrderDetails {get; set;}
      ....
    
    
      public decimal TotalPrice 
      { 
        get 
        {
          OrderDetails.Sum(o => o.TotalPrice);
        }
    
      }
    }
    

    【讨论】:

    • 这看起来很简单。只是想澄清一下,我已经有另一个名为Order 的课程。那么我应该在那个班级而不是在我的OrderDetails 班级中做这个 linq 吗?
    • 是的,Order 类(或您命名的任何名称)是您希望 LINQ 表达式对 OrderDetails 中的所有 TotalPrice 属性求和的地方。 OrderDetails 类中的 TotalPrice 属性只需将数量乘以单价即可。
    • 谢谢你,它的工作,但我认为我的 linq 在GetTotal() 方法中有问题。价值观有问题。例如:Quantity 是 3,UnitPrice 是 275。保存到 TotalPrice 的值应该是 825,但不知何故会出现 43850。
    • 正如我在答案中所说,您不应该尝试从您的 orderdetails 类中的数据库中获取总数(或者实际上直接从任何模型中获取)。您应该考虑使用您的模型创建服务或存储库以访问数据
    • 如果您刚刚开始,请看这里...docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/…。您可能需要谷歌实体框架服务模式以获取更多信息
    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多