2011-10-27 41 views
2
的常量值

以下是错误:无法创建类型为'mvcinfosite.ViewModels.GrpSearchHolder'的常量值。在此上下文中仅支持基本类型(如Int32,String和Guid)。表达式树错误:无法创建类型为

我该如何解决该错误。 我做一个小例子来向你展示我的问题。在我的真实项目中,MyGrp1,MyGrp2,MyGrp3被ListBox替代。我用它来过滤我的数据。

 public class MyGroupHolder 
     { 
      public string GrpName { get; set; } 
      public List<int ?> ListSelectedGrpDescID { get; set; } 
     } 


     public ActionResult Index() 
     { 
      //Database Context 
      DBEntities db = EntityFactory.GetEntity(); 

      //Variables 
      List<MyGroupHolder> ListGrpHolder = new List<MyGroupHolder>(); 

      //Imagine a 3 listbox (MyGrp1,MyGrp2,MyGrp3) 
      //Each listbox contains selected value. 
      MyGroupHolder MyGrp1 = new MyGroupHolder(); 
      MyGrp1.GrpName = "Grp 1 Test"; 
      MyGrp1.ListSelectedGrpDescID = new List<int?>(); 
      MyGrp1.ListSelectedGrpDescID.Add(55); 


      MyGroupHolder MyGrp2 = new MyGroupHolder(); 
      MyGrp2.GrpName = "Grp 2 Test"; 
      MyGrp2.ListSelectedGrpDescID = new List<int?>(); 
      MyGrp2.ListSelectedGrpDescID.Add(56); 


      MyGroupHolder MyGrp3 = new MyGroupHolder(); 
      MyGrp3.GrpName = "Grp 3 Test"; 
      MyGrp3.ListSelectedGrpDescID = new List<int?>(); 
      MyGrp3.ListSelectedGrpDescID.Add(57); 

      ListGrpHolder.Add(MyGrp1); 
      ListGrpHolder.Add(MyGrp2); 
      ListGrpHolder.Add(MyGrp3); 

      //Getting a list of Locations base on the Group Filter 
      var ListLocation = db.Locations.Where(p => ListGrpHolder.Any(pg => pg.ListSelectedGrpDescID.Count == 0 || p.GroupLocations.Select(sg => sg.GrpDescID).Intersect(pg.ListSelectedGrpDescID).Any())).ToList(); 


      return View(); 
     } 

回答

1

您不能将对象从您的应用程序传递给linq-to-entities查询。您必须提取值并将它们作为条件传递。刚开始您的查询的显示问题:

.Where(p => ListGrpHolder.Any(... 

应该如何SQL服务器负责执行LINQ到实体查询知道什么ListGrpHolder是(它生活在你的应用程序的内存),和什么样的价值包含?

我不完全理解你的查询和它应该做什么,只是你必须严格区分linq-to-entities和linq-to-objects。第一个是在SQL服务器上执行的,它只允许传递简单的类型进行查询。第二个是在你的应用程序中执行的,你可以为它们使用任何对象和linq构造,但是如果你想将它与来自SQL server的数据一起使用,你必须首先将它们全部加载到你的应用程序中,并在应用程序的内存中进行过滤服务器。

+0

是否有自定义表达式树将我的查询转换为有效表达式的方法? –

0

转换查询到db.Locations 其中mycalculatedlocalids.Contains(l.id) 选择L使用

从升;

IQueryable包含提供程序信息,IEnumerable(ListGrpHolder)不包含。 这就是为什么你不能在sql server上运行你的查询。

0

我将查询转换为使用LINQ而不是Lambda方法。当用LINQ语法编写查询时,我更容易阅读它们。

db.Locationpg.ListSelectedGrpDescID.Count == 0有什么关系?如果它是0,db.Location应该返回什么?我现在留下了这部分查询。

尝试查找解决方案时,将问题分解成步骤可能是一个好主意。这是迈向解决方案的第一步。

首先,我们可以将ListGrpHolder ID重构为另一个语句。这将只返回int值,并使ListLocation查询更易于阅读。

var SelectedIds = ListGrpHolder.Select(pg => pg.ListSelectedGrpDescID).SelectMany(i => i); 
var ListLocation = (from loc in db.Locations 
        from grp in loc.GroupLocations 
        where SelectedIds.Contains(grp.GrpDescID) 
        select loc).ToList(); 

如果我们无法简化或改变查询以获得您需要的结果,那么我们可以使用表达式树进行研究。

相关问题