我有一个查询数据库的 LINQ 查询(我正在使用 LINQ to SQL)。该查询作为独立的工作正常,但是当我将其放入已编译的查询中时,调用它时会出现错误。
错误,
Exception thrown: 'System.NotSupportedException' in System.Data.Linq.dll Additional information: Member 'StaffManager.Employee.Key' there is no conversion to SQL that are supported.
这是我一直在使用的查询,并且有效。
public static ObservableCollection<Employee> EmployeesInSection(DatabaseDataContext database, string section)
{
return new ObservableCollection<Employee>(database.Staff_Time_TBLs
.Where(staff => staff.Section_Data == section)
.Select(staff => new Employee(staff.Staff_No ?? -1,
staff.Staff_Name_First, staff.Staff_Name_Second))
.ToList()
.GroupBy(staff => staff.Key)
.Select(staff => staff.First())
.OrderBy(staff => staff.Key)
.ToList());
}
这是 Employee 类
,Key
似乎出现了问题。
public class Employee
{
public int Key { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public string FullName => FirstName + " " + SecondName;
public Employee(int key, string first = null, string second = null)
{
Key = key;
FirstName = first;
SecondName = second;
}
}
这是编译后的查询和调用该查询的方法,
public static class CompiledQueries
{
public static Func<DatabaseDataContext, string, IEnumerable<Employee>>
sectionEmployess = CompiledQuery.Compile((DatabaseDataContext database, string section) =>
database.Staff_Data_TBLs.Where(staff => staff.Section_Data == section)
.Select(staff => new Employee(staff.Staff_No ?? -1,
staff.Staff_Name_First, staff.Staff_Name_Second))
.ToList()
.GroupBy(staff => staff.Key)
.Select(staff => staff.First())
.OrderBy(staff => staff.Key));
}
还有方法,这里就出现错误了。
public static ObservableCollection<Employee> EmployeesInSection(DatabaseDataContext database, string section)
{
return new ObservableCollection<Employee>
(CompiledQueries.sectionEmployess(database, section));
}
我不知道为什么这在编译查询中不起作用,但在普通 LINQ 查询中却可以正常工作。感谢您花时间提供帮助。
最佳答案
这个问题的答案是我试图在无法使用的东西上使用CompiledQuery
类。 LINQ 仅在涉及 SQL 时才可以使用此类,而下面的这部分查询则不是。
.Select(staff => new Employee(staff.Staff_No ?? -1,
staff.Staff_Name_First, staff.Staff_Name_Second))
.ToList()
.GroupBy(staff => staff.Key)
.Select(staff => staff.First())
.OrderBy(staff => staff.Key)
.ToList());
因此,为了使这项工作正常进行,第一部分被放入已编译的查询中,
public static class CompiledQueries
{
public static Func<DatabaseDataContext, string, IQueryable<Staff_Time_TBL>>
sectionEmployess = CompiledQuery.Compile((DatabaseDataContext database, string section) =>
database.Staff_Time_TBLs.Where(staff => staff.Section_Data == section));
}
然后在方法中调用已编译的查询并将 LINQ 的第二部分集成到该方法中。
对于任何感兴趣的人,最初我认为这是一个足够复杂的查询,值得尝试 CompiledQuery
,其最终目标是提高应用程序的性能。然而,由于 CompiledQuery
部分非常简单,最终我收获甚微。
关于c# - System.NotSupportedException 使用已编译的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910230/