Linq to sql 无法创建“T”类型的常量值

Linq to sql 无法创建“T”类型的常量值,linq-to-sql,c#-4.0,Linq To Sql,C# 4.0,我有一张名为“主题”的桌子 我还有一个叫做分配的表,它存储了主题的分配 我有一个Datagridview,它由分配表中的主题分配填充 现在我需要获取Datagridview中没有的主题 这样做 我从ObjectContext获取所有主题 现在我得到了从Datagridview分配的所有主题,它会返回一个InMemory集合 现在我使用LINQ.EXCEPT方法过滤结果,但它引发了以下异常, 无法创建ObjectContext类型的常量值。此上下文中仅支持基本类型“如Int32、String和Gu

我有一张名为“主题”的桌子

我还有一个叫做分配的表,它存储了主题的分配

我有一个Datagridview,它由分配表中的主题分配填充

现在我需要获取Datagridview中没有的主题

这样做

我从ObjectContext获取所有主题 现在我得到了从Datagridview分配的所有主题,它会返回一个InMemory集合 现在我使用LINQ.EXCEPT方法过滤结果,但它引发了以下异常, 无法创建ObjectContext类型的常量值。此上下文中仅支持基本类型“如Int32、String和Guid”

下面是我的代码

    public static IOrderedQueryable<Subject> GetSubjects()
    {
        return OBJECTCONTEXT.Subjects.OrderBy(s => s.Name);
    }

    private IQueryable<Subject> GetAllocatedSubjectsFromGrid()
    {
          return (from DataGridViewRow setRow in dgv.Rows          
                    where !setRow.IsNewRow
                    select setRow.DataBoundItem).Cast<Allocation>()  //I know the Problem lies somewhere in this Function
                    .Select(alloc =>alloc.Subject).AsQueryable();
    }

    private void RUN()
    {
        IQueryable<Subject> AllSubjects = GetSubjects(); //Gets

        IQueryable<Subject> SubjectsToExclude = GetAllocatedSubjectsFromGrid();

        IQueryable<Subject> ExcludedSubjects = AllSubjects.Except(SubjectsToExclude.AsEnumerable());   
        //Throwing Me "Unable to create a constant value of type 'OBJECTCONTEXT.Subject'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."
    }

谷歌搜索的结果是,我发现这是因为LINQ无法比较DGV和ObjectcontextFromDB的内存收集记录,时间有点短,没有测试它。但我想你可以试着把这一切都记在记忆里。因此,与其使用

  IQueryable<Subject> AllSubjects = GetSubjects(); //Gets
是吗

List<Subject> AllSubjects = GetSubjects().ToList(); //

List<Subject> SubjectsToExclude = GetAllocatedSubjectsFromGrid().ToList();    

List<Subject> ExcludedSubjects = AllSubjects.Except(SubjectsToExclude);       

我通过比较Where子句中的键而不是使用Except来解决这个问题

因此,不是:

var SubjectsToExclude = GetAllocatedSubjectsFromGrid();
var ExcludedSubjects = AllSubjects.Except(SubjectsToExclude.AsEnumerable());
更像是:

var subjectsToExcludeKeys =
   GetAllocatedSubjectsFromGrid()
   .Select(subject => subject.ID);

var excludedSubjects =
   AllSubjects
   .Where(subject => !subjectsToExcludeKeys.Contains(subject.ID));
不过,我在猜测您的实体的键是什么样子的


这允许您将所有内容都保存在实体框架中,而不是将所有内容都放到内存中。

这非常有效,但有一个潜在的“问题”需要注意:如果不同的列表不相同,即,如果一个列表包含子对象,另一个则不起作用。要注意的事情。