1

This is how i use linq with my entity. All i want to do is to be able to add condition dinamically. I have conditions in string. For example notes == 'some words' or DokumentID == 4. I would love to use that somehow as condition in linQ. I can provide the name of column in database and value searched in two different string. But still i don't have idea how to add it to my linq. Here is my code from program:

        ListImport.Clear();
        using (var db = new Minorlex_MPIPSEntities())
        {

            var query = from s in db.tbl_Dokumenty
                        where s.IdDokumentu == 15
                        select s;

            foreach (tbl_Dokumenty Dokument in query)
            {
                ListImport.Add(Dokument);
            }
        }

and i want to try if i can take the variable string and use it like status in here. To use a variable in string and provide it to linq with added condition to it.

query.Where(x => x.status < 0);

ironzionlion
  • 832
  • 1
  • 7
  • 28
Whencesoever
  • 2,218
  • 15
  • 26

3 Answers3

3

You can do that with Dynamic LINQ.

Just Install-Package System.Linq.Dynamic, include the System.Linq.Dynamic namespace, and you'll have versions of the LINQ methods (Where, OrderBy, etc) that take strings and parse them.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
0

for dynamic condition you can use following changes in code

   ListImport.Clear();
    using (var db = new Minorlex_MPIPSEntities())
    {

        var query = from s in db.tbl_Dokumenty
                    where s.IdDokumentu == 15 || s.DynamicCondition
                    select s;

        foreach (tbl_Dokumenty Dokument in query)
        {
            ListImport.Add(Dokument);
        }
    }
Dane
  • 20
  • 2
0

If you need more control, this is what I've just came up with:

private IList<TEntity> Condition<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> propertySelector, TProperty propertyValue)
        where TEntity :class 
    {
        PropertyInfo property = (PropertyInfo)((MemberExpression)propertySelector.Body).Member;
        ParameterExpression typeParameter = Expression.Parameter(typeof(TEntity));

        MemberExpression propertyExpression = Expression.Property(typeParameter, property);

        using (Minorlex_MPIPSEntities entities = new Minorlex_MPIPSEntities())
        {

            BinaryExpression criteriaExpression = 
                Expression.Equal(propertyExpression, Expression.Constant(propertyValue));

            Expression<Func<TEntity, bool>> condition = 
                Expression.Lambda<Func<TEntity, bool>>(criteriaExpression, typeParameter);

            IEnumerable<TEntity> query = entities.Set<TEntity>().Where(condition);

            return query.ToList();
        }
    }

just pass a property selector expression and a value. you may extend the method with custom set of operations(now there's simple equality, see criteriaExpression)

Andrew
  • 3,648
  • 1
  • 15
  • 29