我可以在我的方法中使用动态实体上下文吗?

本文关键字:实体 动态 上下文 我的 方法 我可以 | 更新日期: 2023-09-27 18:30:26

我有一种用于网格视图排序和分页的方法,我正在尝试将其用于泛型类型,但我正在努力弄清楚如何使实体上下文(MyContext)和表(tblReports)动态变量 - 任何人都可以帮助我吗?

protected void PopulateGridView<T>(GridView grid)
{
    string columnToSortBy = (string)(ViewState["gridview_sortbycolumn"] ?? string.Empty);
    SortDirection sortDirection = (SortDirection)(ViewState["gridview_sortdirection"] ?? SortDirection.Descending);
    int pageIndex = (int)(ViewState["gridview_pageindex"] ?? 0);
    int pageSize = grid.PageCount;
    using (MyContext db = new MyContext())
    {
        if (columnToSortBy != string.Empty)
        {
            var query = db.tblReports.OrderBy(columnToSortBy + " " + sortDirection).Skip(pageIndex * pageSize);
            grid.DataSource = query.ToList();
        }
        else
        {
            string defaultColumn = string.Empty;
            foreach (var field in typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
            {
                defaultColumn = field.Name.Remove(field.Name.IndexOf(">")).Replace("<", string.Empty);
                break;
            }
            var query = db.tblReports.OrderBy(defaultColumn).Skip(pageIndex * pageSize);
            grid.DataSource = query.ToList();
        }
        grid.PageIndex = pageIndex;
        grid.DataBind();
    }
}

我可以在我的方法中使用动态实体上下文吗?

设法

通过按照@Jeroen的建议将实体表作为参数传递并将 linq 查询结果转换为泛型类型来使其工作。

这是任何感兴趣的人的最终代码:

protected void PopulateGridView<T>(GridView grid, DbSet entityTable)
{
    string columnToSortBy = (string)(ViewState["gridview_sortbycolumn"] ?? string.Empty);
    SortDirection sortDirection = (SortDirection)(ViewState["gridview_sortdirection"] ?? SortDirection.Descending);
    int pageIndex = (int)(ViewState["gridview_pageindex"] ?? 0);
    if (columnToSortBy != string.Empty)
    {
        grid.DataSource = entityTable.OrderBy(columnToSortBy + " " + sortDirection).Cast<T>().ToList();
    }
    else
    {
        // use linq reflection to get the first entity field name to sort by
        string defaultColumn = string.Empty;
        foreach (var field in typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
        {
            defaultColumn = field.Name.Remove(field.Name.IndexOf(">")).Replace("<", string.Empty);
            break;
        }
        grid.DataSource = entityTable.OrderBy(defaultColumn).Cast<T>().ToList();
    }
    grid.PageIndex = pageIndex;
    grid.DataBind();
}