1

I currently have multiple methods that do pretty much the same thing but just query different tables.

I am trying to use only one method and pass the method parameters instead so i can skip creating multiple methods and neaten my code.

This is what i have currently:

MyEntityModel entity = new MyEntityModel();

private void loadData()
{
    var query = from data in entity.Table1
               select data;

    myDataGrid.ItemsSource = query.ToList();
}

I want something like this:

MyEntityModel entity = new MyEntityModel();

private void loadData(DataGrid dataGrid, Table myTable )
{
    var query = from data in entity.myTable
               select data;

    dataGrid.ItemsSource = query.ToList();
}

I'm unsure what Type parameter i should pass for myTable I tried passing it as a System.Data.Entity.DbSet and as a MyEntityModel

Is something like this even possible using LINQ?

4

2 回答 2

0

虽然懒惰的答案是一种选择,但另一种选择是接受 anIQueryable作为参数:

private void LoadData<T>(DataGrid dataGrid, IQueryable<T> query)
{
    dataGrid.ItemsSource = query.ToList();
}

然后你会这样称呼它:

LoadData(dataGrid, entity.Table1);
于 2013-08-26T16:46:35.197 回答
0

您可以创建从提供的实体类型的 DbSet 实例返回所有数据的通用方法:

MyEntityModel entity = new MyEntityModel();

private void LoadData<T>(DataGrid dataGrid)
    where T : class
{    
    dataGrid.ItemsSource = entity.Set<T>().ToList();
}

像这样使用它

LoadData<Table1>(myDataGrid); // Table1 is a entity type name
于 2013-08-26T16:11:37.803 回答