0

Basically I have an HTML form with about 20 fields. I create an object based on what the user entered on the form and what he did not enter, I set it to null. I want to get things that match on the database

I currently have something simple like:

IQueryable<Item> query = context.Items;
            if (i.Height!=null)   //i is the item from the HTML form
            {
                query = query.Where(c => c.Height == i.Height);
            }

This currently gives me all of the items that match just the height field that the user gave. I need to gather just the items that match the user description, ALL of the descriptions on the HTML form

I can't think of a way of doing this without a huge block of conditional logic. How would I do this?

john
  • 33
  • 5
  • Ideally you should have an unique key to match the db. For instance Employee name or code in employee table must be unique so you can match with that and update the table. You can combine description & name to create uniqueness comparing that against your db will reduce the load rather than comparing against all records – Eldho Oct 08 '18 at 07:14

1 Answers1

0

You should use expression trees. Take a look here. You can combine expressions to meet your requirements like check for nulls using:

// Create null checker property != null
var nullCheck = Expression.NotEqual(property, Expression.Constant(null, typeof(object)));
// Add null checker in front of the condition using &&
condition = Expression.AndAlso(nullCheck, condition);

Where condition can be your specific condition like checking each property of HTML form data to meet your requirements like c => c.Height == i.Height.

To get more about Expression Trees take a look here.

Bardr
  • 2,319
  • 2
  • 12
  • 21
  • Please update the link to https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/how-to-use-expression-trees-to-build-dynamic-queries – Praveen Rai Oct 08 '18 at 07:39