【问题标题】:Filtering on projected property field in LINQ to entities query过滤 LINQ to entity 查询中的投影属性字段
【发布时间】:2014-03-28 02:07:10
【问题描述】:

下面的 LINQ to Entities 查询会执行一个子查询,并将其结果投射到MyViewModel

我希望在SubModelText 属性中使用myText 字符串变量获取所有ProjectedModel 对象。

var items = (from t1 in db.MyTable
                select new MyModel
                {
                    Id = t1.MyId,
                    SomeItems = (from s1 in db.MyOtherTable
                        where s1.LinkedId == t1.Id
                        select new SubModel
                        {
                            Id = s1.Id,
                            Text = s1.Text
                        })
                }).ToList();

伪代码如下所示:

string myText = "abc";
items = items where SomeItems.Text contains myText

【问题讨论】:

    标签: c# linq linq-to-entities


    【解决方案1】:

    如果您想获取所有 任何 子项目具有给定文本的项目,那么编写起来很容易:

    items = items.Where(item => 
        item.SomeItems.Any(subItem => subItem.Text.Contains(myText)));
    

    如果您希望所有项匹配,请使用All。事实上,您的要求目前不完整,因为他们假设只有一个子项目。 (如果您知道总会有一个子项,那么不要将SubItems 设为集合,将其设为单个项,并获取查询中的第一项。)

    【讨论】:

    • 对此的测试导致“此方法不支持具体化查询结果。”
    • 只是 .ToList()'ed SomeItems。排序。谢谢。
    【解决方案2】:

    你可以这样做

    更新代码

    item.Where(w => myText.Contains(w.Text));  
    

    或者你可以使用.StartsWith().EndsWith()

    参考:LIKE

    我的回答已经过时,或者它可能对你没有帮助,但还有一些可能对你有帮助的东西

    var selectItedm = (from a in item   
                      where SqlMethods.Like(a.Text,"%"+myText+"%")  
                      select new {a.Id,a.Text}).ToList();  
    

    您可以使用更多 SqlMethods 只需包含 System.Data.Linq.SqlClient; 参考

    【讨论】:

    • 感谢您的回复。我使用过 contains 但希望在嵌套对象的属性上使用它。
    • 我不想过滤 Id,我想过滤 SubModel 中的 Text 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多