【问题标题】:MVC/LINQ - nested where request who doesn't workMVC/LINQ - 嵌套在哪里请求谁不工作
【发布时间】:2016-10-10 11:09:57
【问题描述】:

我在 Razor 视图中遇到嵌套 Where 子句请求的问题(带有 EF 6 的 Asp.net MVC):

这是我的请求(模型是来自控制器的 IEnumarable,它具有正确的值):

 @foreach (var item in Model.Where(p => (p.user.SellGoods.Where(g => g.IsBuy == false)) != null))

我的好模特是:

    [Key]
    public String Name { get; set; }

    public String UrlImage { get; set; }

    [MinLength(10), MaxLength(500)]
    public String Description { get; set; }

    public float Price { get; set; }

    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }

    [DataType(DataType.Date)]
    public Nullable<DateTime> EndOfAuction { get; set; }

    public virtual EnumStrategy Strategy { get; set; }

    public int UserID { get; set; }

    public virtual User user { get; set; }

    public Boolean IsBuy { get; set; }

    public int CurrentAuctionWinner { get; set; }

还有我的用户模型:

    [EmailAddress]
    public String Mail { get; set; }

    [Column("SellGoods")]
    public virtual ICollection<Good> SellGoods { get; set; }

    [Column("BuyGoods")]
    public virtual ICollection<Good> BuyGoods { get; set; }

    public virtual Address ShippingAddress { get; set; }

    public virtual Address BillingAdress { get; set; }

    [Range(0.00d, 10.00d)]
    public double Rate { get; set; }

根据我目前的要求,我得到了一位成员的所有好评,比如 (g =&gt; g.IsBuy == false) 不起作用..

有人知道出了什么问题吗?

非常感谢!

【问题讨论】:

  • Where() 总是返回 IEnumerable&lt;Good&gt; 因此总是非空的。也许您的意思是Model.Where(p =&gt; p.user.SellGoods.Any(g =&gt; g.IsBuy)(其关联用户在其SellGoods 集合中至少有一个Good 未标记为IsBuy 的所有商品)

标签: c# asp.net linq asp.net-mvc-5 entity-framework-6


【解决方案1】:

如果在Where() LINQ 扩展方法中不满足条件,则返回一个空的IEnumerable。所以你的条件永远不会满足。使用Any() 而不是Where() != null,如下所示:

@foeach (var item in Model.Where(p => p.user.SellGoods.Any(g => !g.IsBuy)))

【讨论】:

    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多