c# - 如何在模型绑定(bind)中使用 Group By 查询

标签 c# asp.net entity-framework linq model-binding

在我的 ASP.NET Web 窗体应用程序中,我使用(模型绑定(bind)/ Entity Framework )。

我想在 Gridview 中显示 Linq 查询(分组依据)的结果,但我不能!!

<asp:GridView runat="server" ID="UsersGrid"
        ItemType="myApp.Models.users" DataKeyNames="id"
         SelectMethod="UsersGrid_GetData"
         AutoGenerateColumns="false">
    <Columns>
        <asp:DynamicField DataField="Fonction" />
        <asp:DynamicField DataField="Count" />
    </Columns>
</asp:GridView>

背后代码:

public IQueryable<users> UsersGrid_GetData()
{
    ModelData db = new ModelData();

    var result = from d in db.users
                 group d by d.Fonction into grouped
                 select new
                 {
                     Fonction = grouped.Key,
                     Count = grouped.Count()
                 };

    return result.AsQueryable();        
}

我有这个错误:

Cannot implicitly convert type 'System.Linq.IQueryable<>' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

最佳答案

您正在创建匿名类型的对象并尝试将其转换为可查询。这就是您收到此错误的原因。

试试这个: 方法 1:如果您想使用用户模型本身,其中“用户”具有您需要绑定(bind)到 GridView 的属性。

  public IQueryable<users> UsersGrid_GetData()
    {
        ModelData db = new ModelData();

        var result = from d in db.users
                 group d by d.Fonction into grouped
                     select new users
                     {
                         Fonction = grouped.Key,
                         Count = grouped.Count()
                     };

        return result;

    }

方法 2:使用不同的模型 'p'

  public IQueryable<p> UsersGrid_GetData()
    {
        ModelData db = new ModelData();

        var result = from d in db.users
                 group d by d.Fonction into grouped
                     select new p
                     {
                         Fonction = grouped.Key,
                         Count = grouped.Count()
                     };

        return result;

    }

    public class p
    {
        public int? Fonction { get; set; }
        public int Count { get; set; }
    }

根据您的应用程序提供一个有效的名称,而不是“p”。还要在 GridView 中进行必要的更改(您可能必须更改“ItemType =“myApp.Models.users”)。

关于c# - 如何在模型绑定(bind)中使用 Group By 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173010/

相关文章:

ASP.NET Web 应用程序

mysql - 检查日期中的 Null Asp、VB、SQL

asp.net-mvc - 将模型用于多种目的

c# - 递归蛇寻路算法方法

asp.net - 如何使用 ASP.NET 和 iframe 跨域对用户进行身份验证?

c# - 线程化 HTTP Post 应用程序

entity-framework - .net core Entity Framework 两种关系可以使用相同的外键

asp.net-mvc - 使用 sqlserver Express 时 Entity Framework 不创建数据库

c# - 静态类是否创建实例? msdn 说我没有,但为什么构造函数呢?

c# - C# 中是否有任何 CSV 读取器/写入器库?