我有一张名为主题的表格,
我有一个名为分配的另一个表,它存储了主题的分配
我有 Datagridview ,其中填充了分配表中的主题分配
现在我需要在 Datagridview
中获取不的主题要做到这一点
“无法创建类型的常量值”ObjectContext.Subjects“在此上下文中仅支持基本类型(例如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无法比较InMemory集合(DGV记录)和Objectcontext(FromDB)
答案 0 :(得分:2)
时间有点短暂,没有测试过。但我想你可以试着把它全部记在内存中。所以不要使用
IQueryable<Subject> AllSubjects = GetSubjects(); //Gets
你做
List<Subject> AllSubjects = GetSubjects().ToList(); //
List<Subject> SubjectsToExclude = GetAllocatedSubjectsFromGrid().ToList();
List<Subject> ExcludedSubjects = AllSubjects.Except(SubjectsToExclude);
答案 1 :(得分:0)
我通过比较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));
(我猜测你的实体的关键是什么样的。)
这允许您将所有内容保留在Entity Framework中,而不是将所有内容都放入内存中。