简体   繁体   English

C#Linq“ GroupBy”

[英]C# Linq “GroupBy”

I have a problem with a code that i wrote today. 我今天编写的代码有问题。 I want to select some rows from the database and group them by one of the columns. 我想从数据库中选择一些行,并按列之一对其进行分组。 This is my code: 这是我的代码:

public class Classes
{
    public IQueryable<ClassData> HomeWorkList { get; set; }
}
public class ClassData
{
    public string Name { get; set; }
    public string English { get; set; }
}

var classesCustomViews = new Classes { 
    HomeWorkList = _repositoryClasses.GetRecords()
        .GroupBy(s => new { s.Name, s.English })
        .Select(s => new ClassData 
            { 
                English = s.Key.English, 
                Name = s.Key.Name 
             })
    };    
return PartialView(classesCustomViews);

This is the error that I get: 这是我得到的错误:

System.Data.SqlClient.SqlException: Invalid column name 'English'. System.Data.SqlClient.SqlException:无效的列名称“英语”。 Invalid column name 'English'. 无效的列名“英语”。 Invalid column name 'English'. 无效的列名“英语”。

Since you're not pulling back any aggregate info other than your keys, you should be able to do it without the grouping by just using Distinct assuming that you are working with IQueryable up the stack to the database: 由于除了键之外,您没有撤回任何聚合信息,因此,只需使用Distinct(假定您正在使用IQueryable将堆栈扩展到数据库),就可以在不进行分组的情况下进行分组:

var classesCustomViews = new Classes { 
    HomeWorkList = _repositoryClasses.GetRecords()
        .Select(s => new ClassData 
            { 
                English = s.English, 
                Name = s.Name 
             })
        .Distinct()
    };  

If you still get an error, I would check your mapping and table to make sure that the table column names didn't change. 如果仍然出现错误,我将检查您的映射和表,以确保表列名没有更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM