【问题标题】:Select EF entities that have all the given Tags (where tag is an EF entity)选择具有所有给定标签的 EF 实体(其中标签是 EF 实体)
【发布时间】:2012-06-26 08:37:55
【问题描述】:

我有以下情况: 一个“对话”实体/表,它有多个与之关联的标签。 Tag 也是一个实体/表 - 键/id 是 tagName(一个字符串)。

在客户端 (javascript) 处理标签时,我使用字符串数组。

现在我想检索所有具有 all 给定标签的对话。


输入是一个字符串数组,输出应该是一个对话集合

我试过了:

var filterTags = new List<EFModels.Tag>();
foreach (var tagName in tags)
            {
               filterTags.Add(new EFModels.Tag() { Name = tagName});
            }

var conversations = from c in context.Conversations where !c.Tags.Except(filterTags).Any() select c ;

这个问题是:Unable to create a constant value of type 'EFModels.Tag'. Only primitive types or enumeration types are supported in this context - 这是有道理的。

现在我该如何选择?最好的方法是什么? (我还是想用linq,不写sql select)

【问题讨论】:

    标签: c# .net linq entity-framework linq-to-entities


    【解决方案1】:

    您可以将 c.Tags 投影到标签名称。

    我猜应该是这样的

    var conversations = from c in context.Conversations where !c.Tags.Select(tag => tag.Name ).Except(filterTags).Any() select c ;
    

    其中 filterTags 是包含标签名称的字符串列表

    【讨论】:

    • 这可以解决问题 - 谢谢。我不得不将查询更改为 var conversations = from c in context.Conversations where !tags.Except(c.Tags.Select(tag => tag.Name)).Any() select c ;现在它可以正常工作了。不过有一件事让我很困扰——性能。我还能做什么/改变以提高查询的性能?
    • 取决于标签名称集合的大小。我相信性能不会受到影响。无论如何,由于标签名称在内存中,这将生成 sql 查询,这将是.. sth... 其中标签在(tag1,tag2...tagN)。您应该记住,如果标签名称集合太长(超过 2000 个元素),则查询将失败,因为 in 语句最多支持 2000 个参数。
    • 感谢您提供有关参数的提示 - 我将不得不运行一些测试以查看性能衰减/影响。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多