ista9im ista9im - 1 month ago 12
ASP.NET (C#) Question

How to use Group By query in Model Binding

In my ASP.NET Web Forms application, I use (Model Binding / Entity Framework).

I want to display the result of my Linq Query (group by) in a Gridview, but I can't !!

<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>


Code Behind:

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();
}


I have this error :


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

Answer

You are creating object of anonymous type and trying to convert it as Queryable. That is why you are getting this error.

Try this: Method 1: If you would like to use the users model itself where 'users' have the properties which you needed to bind to grid view.

  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;

    }

Method 2: Use a different model '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; }
    }

Instead of 'p' give a valid name as per your application . Also make necessary changes in grid view (You may have to change " ItemType="myApp.Models.users").

Comments