0

I am using entity framework 4.0. I have two tables, movies and Genres in a relation N:N. In the database I have an itermediate table but when I create the edmx I have only two tables. It is created two entities:

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; }
    }

In my repository, I would like to create a method that return all the movies that al least has one of the generes that is passed in a list of genres as parameter of the method.

Also, I need to compare not directly the object Genre, but the IDGenre, because the object that I have in the list of parameters are different to the objects genre that I have in the collection of the object movie.

I try to do this:

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

But I get this error:

LINQ to Entities does not recognise the method 'System.Collections.Generic.List1[System.Int64] ToList[Int64](System.Collections.Generic.IEnumerable1[System.Int64])' of the method, and this method can't be translate to store expresion.

EDIT: I have tried removing ToList() in both case. I use this code:

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

And in this case I get this error:

It can't be created a constant value of type Genres. It is only admited the primitive types ('such as Int32, String y Guid') in this context.

Thanks.

4

1 回答 1

1

Intersect如果你正在使用,你真的需要Any吗?尝试使用 aJoin因为您试图将列匹配在一起。

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());
于 2013-06-17T14:47:40.357 回答