Linq 到实体不工作

Linq To Entity Not Working

我的模型域中有三个 poco 类,如下所示 一切正常我可以对所有三个进行 crud 操作,但是在客户索引视图或详细信息视图中,我想计算订单数量和服务率字段的总和,我 运行 以下查询但它们总是 return 零

在索引视图中

 @item.Orders.Count
 @item.Orders.Sum(O=>O.Service.Rate)

并详细查看

  @Model.Orders.Count
  @Model.Orders.Sum(o=>o.Service.Rate)

我也曾尝试在带有 viewBag 的控制器中使用 linq,但它返回 运行 零

 ViewBag.RateX = customer.Orders.Count;
 ViewBag.Sum = customer.Orders.Sum(o => o.Service.Rate);

我查看了 sql 中的订单 table ,table 中同时存在 customerID 和 ProductID,主键值为 customer 和 service table .

我已经搜索了 msdn 和 google 但找不到问题所在?

 public class Customer



{
    public Customer()
    {
        this.Orders = new HashSet<Order>();
    }
    public int CustomerID { get; set; }

    public String CustomerCode { get; set; }
    public String FistName { get; set; }
    public String LastName { get; set; }
    public String Email { get; set; }
    public String Mobile { get; set; }
    public String Description { get; set; }
    public ICollection<Order> Orders { get; set; }

}

}

  public class Product
{
    public int ProductID { get; set; }
   [Required(ErrorMessage="Please Enter Product Name")]
    public String Name { get; set; }
    [Required(ErrorMessage="Pleas Eneter A Rate For this Product")]
    public int Rate { get; set; }
    public String Description { get; set; }
    public ICollection<Order> Orders { get; set; }
}
 public class Order
{
    public int OrderID { get; set; }
    public DateTime Date { get; set; }
    [ForeignKey("Service")]
    public int ProductID { get; set; }
    [ForeignKey("ProductID")]
    public Product Service { get; set; }
    public String Description { get; set; }
    [ForeignKey("customer")]
    public int CustomerID { get; set; }
    [ForeignKey("CustomerID")]
    public Customer customer { get; set; }
}

} 这是客户控制器 public 动作结果索引() {

        return View(db.Customers.ToList());
    }
public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Customer customer = db.Customers.Find(id);
        if (customer == null)
        {
            return HttpNotFound();
        }
       var order = from s in db.Orders where s.customer.CustomerID == customer.CustomerID select s;
       var rate = order.Sum(o => o.Service.Rate);
       ViewBag.Rate = rate;
       ViewBag.RateX = customer.Orders.Count;
       ViewBag.Sum = customer.Orders.Sum(o => o.Service.Rate);
        return View(customer);
    }

非常感谢。

其实我做的是延迟加载

如果 EF 支持延迟加载,我应该在我的 classess 中添加 virtual 关键字,如下所示

顺序class

public virtual Product Service { get; set; } 

并在客户中 class

 public virtual ICollection<Order> Orders { get; set; }