2013-03-06 75 views
0

我刚接触C#开发,并且有一些问题。 我希望你帮忙。实体框架Datagridview筛选器

我有2个实体相关的多对多 - 电影和流派。 我需要在datagridView中显示所有电影,其中movies.genres包含在listBoxGenres中选择的流派。

我试试这个代码:

moviesDBEntities myContext = new moviesDBEntities(); 

var myQuery = from movie in myContext.Movies 
       where movie.genre.Contains(ListBoxGenres.SelectedItem) 
       select movie; 


dgvMovies.Datasource = myQuery.ToList(); 

的问题是,收到异常错误是这样的:

“无法创建类型的恒定值‘System.Object的’只有原始类型。 ('如Int32,String和Guid')在此上下文中受支持。“

感谢您的帮助的ListBoxGenres.SelectedItem

+0

什么是'ListBoxGenres.SelectedItem'包含在里面? – 2013-03-06 20:26:45

+0

感谢您的帮助。 lstBoxGenres.Datasource = myContext.Genres lstBoxGenres.DisplayMember =“idGenre”; lstBoxGenres.ValueMember =“流派”; 我没有ListBoxGenres.SelectedItem.Value属性。 – Nonick 2013-03-06 21:08:30

回答

0

here

在查询中引用非标量变量(例如实体)不支持 。执行此类查询时,会抛出NotSupportedException异常,并显示一条消息,指出“无法创建类型为EntityType的 常量值。在此上下文中仅支持基本类型(如' Int32,String和Guid') “。

尝试重新措辞查询中使用标量变量(在这里我假设类型实体有编号的PK):

var myQuery = from movie in myContext.Movies 
      where movie.genre.Any(g=>g.Id == ((Genre)listBox.SelectedItem).Id) 
      select movie; 
+0

你的回答对我很有帮助。谢谢 – Nonick 2013-03-06 20:51:32

0

使用属性,例如:ListBoxGenres.SelectedItem.Value

var myQuery = from movie in myContext.Movies 
       where movie.genre.Contains(ListBoxGenres.SelectedItem.Value) 
       select movie;