简体   繁体   中英

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'. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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