John Louie Dela Cruz John Louie Dela Cruz - 2 months ago 12
C# Question

Select from table using model properties that is not null

I want to select values from table where my model properties that has a value.
This is my Model.

public class Library
{

public IEnumerable<Books> books { get; set; }
public string BookName { get; set; }
public string Color { get; set; }
public int ShelfNumber { get; set; }
}


I want to select from table where values are equal to my model property that is filled up.

For Example:

public ActionResult(Library lib)
{
var b = _bookService.GetBooks();
lib.books = b.Where(x => // select values from table based on the properties that has a value in my model)
}


How to do this?

Answer

Assuming that properties in Books has same names as properties in Library you are probably looking for something like this:

var b = _bookService.GetBooks();

foreach (PropertyInfo p in typeof(Library).GetProperties())
{
    // skip "books" property
    if (p.Name == "books")
    {
        continue;
    }

    // skip null values from lib
    if (p.GetValue(lib) == null)
    {
        continue;
    }

    // build condition dynamically
    var value = Expression.Constant(p.GetValue(lib));
    var param = Expression.Parameter(typeof (Books));
    var predicate = Expression.Lambda<Func<Books, bool>>(
        Expression.Equal(
            Expression.Property(param, p.Name), 
            value
        ),
        param
    );

    b = b.Where(predicate);
}

b must be queryable, if it is not change first line to var b = _bookService.GetBooks().AsQueryable();

Comments