首页 > 解决方案 > 使用 Lambda 或 Linq 根据子表获取数据

问题描述

我有两张表,它们的产品和价格之间存在一对多的关系。只有当价格表没有超过一个月的相关记录或价格更新日期时,我才想从产品表中获取前 5 个项目。

我试过这个;

        DateTime checkdate = DateTime.Today.AddMonths(-1);

        var test = (from p in main.product
                    from r in main.price
                    where !p.price.Any() && r.UpdateTime >= checkdate

                    select p.main.productid).Take(5);


                    //webservice will check new prices here

所以,每次都返回相同的记录......

标签: c#entity-frameworklinqlambda

解决方案


由于您的条件包含或“仅当价格表没有相关记录价格更新日期超过一个月时。 ”您需要在 where 条件下将运算符 AND ( &&) 更改为 OR ( )。||

var test = (from p in main.product
                    from r in main.price
                    where !p.price.Any() || r.UpdateTime >= checkdate

                    select p.main.productid).Take(5);

推荐阅读