如何在实体框架中进行此查询?

时间:2013-06-17 14:39:04

标签: c# linq many-to-many

我正在使用实体框架4.0。我有两个表,电影和类型N:N的关系。在数据库中,我有一个非常表,但是当我创建edmx时,我只有两个表。它创建了两个实体:

Movies
{
   public Movies()
   {
       this.Genres= new HashSet<Genres>();
   }

  public long IDMovie { get; set; }
  public string Titulo { get; set; }
  public virtual ICollection<Generos> Generos { get; set; }
}



Genres
    {
       public Genres()
       {
           this.Movies= new HashSet<Movies>();
       }

      public long IDGenre { get; set; }
      public string Genre{ get; set; }
      public virtual ICollection<Movies> Movies{ get; set; }
    }

在我的存储库中,我想创建一个方法,返回所有至少有一个类型的电影,这些电影在一个类型列表中作为方法的参数传递。

另外,我需要不直接比较对象类型,而是IDGenre,因为我在参数列表中的对象与我在对象影片集合中的对象类型不同。

我尝试这样做:

myContext.Movies.Where(m=>(m.Genres.Select(gm=>gm.IDGenre).ToList<long>()).Intersect(listGenres.Genres.Select(gl=>gl.IDGenre).ToList<long>()).Any());

但是我收到了这个错误:

LINQ to Entities无法识别方法的'System.Collections.Generic.List 1[System.Int64] ToList[Int64](System.Collections.Generic.IEnumerable 1 [System.Int64])',并且此方法无法转换为存储expresion。

编辑:我在两种情况下都试图删除ToList()。我使用这段代码:

myContext.Movies.Where(m=>(m.Genres.Select(gm=>gm.IDGenre)).Intersect(listGenres.Genres.Select(gl=>gl.IDGenre)).Any());

在这种情况下,我收到此错误:

无法创建Genres类型的常量值。在这种情况下,它只被简化为原始类型(例如Int32,String y Guid')。

感谢。

1 个答案:

答案 0 :(得分:1)

如果您使用Intersect,是否真的需要Any?尝试使用Join,因为您尝试将列匹配在一起。

var compareGenres = listGenres.Genres.Select(gl => gl.IdGenre).ToList();
var matchingMovies = myContext.Movies.Where(m =>
                                        m.Genres.Join(compareGenres,
                                                      g => g.IdGenre,
                                                      cg => cg.IdGenre,
                                                      (g, cg) => g
                                                     ).Any());