General Entity Framework

I have code like:

switch(sort.Column)
{
  case "code":
    model = (sort.Direction == SortDirection.Ascending)
            ? model.OrderBy(x => x.code)
            : model.OrderByDescending(x => x.code);
    break;
  case "name":
    model = (sort.Direction == SortDirection.Ascending)
            ? model.OrderBy(x => x.name)
            : model.OrderByDescending(x => x.name);
    break;
..............
}

I have about 10-15 fields (for example, "code" and "name"), and I do not want to copy and paste the same code with only one difference field name.

Is there any way to generalize the request somehow?

+5
source share
3 answers

You can use reflection (this assumes that codeboth nameare properties, if they are public variables, you will have to change accordingly):

model = (sort.Direction == SortDirection.Ascending)
  ? model.OrderBy( x => x.GetType()
      .GetProperty( sort.Column ).GetValue( x, null ) ) :
  : model.OrderByDescending( x => x.GetType()
      .GetProperty( sort.Column ).GetValue( x, null ) );

, , , . , , . model Foo, :

var prop = typeof( Foo ).GetProperty( sort.Column );

model = (sort.Direction == SortDirection.Ascending)
  ? model.OrderBy( x => prop.GetValue( x, null ) ) :
  : model.OrderByDescending( x => prop.GetValue( x, null ) );

, TargetException, .

+7

, , , .

// inline function
Func<Func<Model, TResult>, Model> Order = criteria => 
{
    return (sort.Direction == SortDirection.Ascending)
            ? model.OrderBy(criteria)
            : model.OrderByDescending(criteria);
}

... code down to switch ...

:

model = Order(x => x.name);

, , - , .

+3

" IP", - / factory/etc. . . - linq. , : http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

You can also drop your own if you want, as it is not too difficult. Create your own custom extension methods that allow you to pass parameters (i.e. sort direction, sort column) about your order and within this extension method. Create your own order using the using statement using the system.linq.expressions namespace. Here is an example of this: http://ronniediaz.com/2011/05/24/orderby-string-in-linq-c-net-dynamic-sorting-of-anonymous-types/

+1
source

All Articles