LINQ to SQL传递对象作为参数

时间:2017-05-03 13:02:24

标签: c# sql asp.net linq-to-sql

要选择使用LINQ to SQL的内容,我们通常会这样做:

        DataClassesDataContext context = new DataClassesDataContext();
        var value = from employee in context.Employees
                               orderby employee.Salary descending
                               select employee;

如果我喜欢30个表并且我想在一个方法中写一次并且只将参数传递给函数来调用这样的表,那该怎么办:

    public void select_function(Parameter1,Parameter2)
{
    DataClassesDataContext context = new DataClassesDataContext();
    var value = from Parameter1 in context.Parameter2
                               orderby Parameter1.Salary descending
                               select Parameter1;
}

甚至可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用LINQ to SQL Data Context对象的GetTable<T>泛型方法。并传递一个表达式进行排序:

public void select_function<T, TProperty>(Expression<Func<T, TProperty>> orderBy)
    where T : class
{
    DataClassesDataContext context = new DataClassesDataContext();
    var value = context.GetTable<T>().OrderByDescending(orderBy);
}

用法:

select_function((Employee e) => e.Salary)

虽然你可以做到

var value = context.GetTable<Employee>().OrderByDescending(e => e.Salary);

没有创建任何方法