至少包含所有的实体框架 [英] Contains At Least All in Entity Framework

查看:161
本文介绍了至少包含所有的实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2实体的在我的分贝。

I have the following 2 entitys in my db.

public class Article
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    // Some code removed for brevity

    public virtual ICollection<Tag> Tags { get; set; }
}


public class Tag
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    // Some code removed for brevity

    public virtual ICollection<Article> Articles { get; set; }

}

我需要基于传递到我的行动标签ID来过滤这些文章。

I need to filter these articles based on the tag IDs that are passed into my action.

public ActionResult FindAll(List<int> tags)
{

    //
    // I need to return all articles which have ALL the tags passed into this method
    //

    var query = ApplicationDbContext.Articles...


}

例如,如果我通过在一,二,三成的动作,只是其中有这3个标签以上条款将被退回。

For example, if I passed in 1, 2, 3 into the action, only articles which had these 3 tags or more would be returned.

我怎样才能做到这一点?

How can I achieve this?

感谢伟大的反应!

您所有的答案产生正确的结果,所以我做了SQL中的一些快速的,基本的分析,这是根据您的查询结果。

All your answers produced the correct result so I did some quick, basic profiling in sql and this was the results based on your queries.

推荐答案

使用的 除了() 和的 任何()

ApplicationDbContext
    .Articles
    .Where(a => tags.Except( a.Tags.Select( t => t.Id ).ToList() ).Any() == false)

除()会给你从第一个列表,其中的项目不要中存在的第二个列表

Except() will give you the items from the first list which do not exist in the second list

EXCEPT运算符产生两个序列之间的差集。
  它只将在第一序列没有出现返回元素
  在第二个。

The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second.

这篇关于至少包含所有的实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆