Page 1 of 1

Dynamic predicates using PredicateBuilder

Posted: Sat 12 Feb 2011 12:11
by sipe16
Hi,

I'm using the latest version of LinqConnect professiona using the MySql provider l and I have the need to create dynamic nested predicates based on provided criteria. I'm trying to do something like the following using PredicateBuilder (http://www.albahari.com/nutshell/predicatebuilder.aspx):

(This is just a very basic example)

Code: Select all

using (var context = new MyDataContext())
{
    var inner = PredicateBuilder.False();
    inner.Or(x => x.ID == 12345);
    inner.Or(x => x.ID == 54321);

    var outer = PredicateBuilder.True();
    outer.And(x => x.AccountID == 111111);
    outer.And(inner);

    var myClasses = context.MyClasses.Where(outer).ToArray();
}
However, the generated SQL only ever results in something to the effect of:

Code: Select all

SELECT id, account_id FROM my_class WHERE :p0
Without any of the predicate clauses.

Has anyone had any luck with dynamic predicates like this? Is there a better way to do this with LinqConnect?

Thanks,
Cyle

Posted: Sat 12 Feb 2011 12:27
by sipe16
I will also add, that due to multiple-data-source requirements, we're not using Entity Developer and the DAL is custom. So, the actual implementation is something more to the effect of the following, and the context.MyClasses in my post above would really be context.GetMyClassList().

*Generic Data Layer*

Code: Select all

public abstract class DbMyClass
{
    public virtual int ID { get; set; }
    public virtual int AccountID { get; set; }
}

public interface IMyDataContext
{
    IQueryable GetMyClassList();
}
*MySQL-specific DAL*

Code: Select all

public class MyDataContext : DataContext, IMyDataContext
{
    [Table(Name = "mydb.my_class")]
    public class MyClass : DbMyClass
    {
        [Column(Name = "id", IsPrimaryKey = true)]
        public override int ID { get; set; }
        [Column(Name = "account_id")]
        public override int AccountID { get; set; }
    }

    public IQueryable GetMyClassList()
    {
        return base.GetTable();
    }
}

Posted: Sat 12 Feb 2011 13:25
by sipe16
I figured it out! My fault :-) I realized that .And and .Or return a new expression and I wasn't overwriting the predicate variable with the new expression.

Posted: Mon 14 Feb 2011 15:12
by StanislavK
Glad to see that the problem was resolved.