Dynamic predicates using PredicateBuilder

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
sipe16
Posts: 8
Joined: Sat 12 Feb 2011 11:59

Dynamic predicates using PredicateBuilder

Post by sipe16 » Sat 12 Feb 2011 12:11

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

sipe16
Posts: 8
Joined: Sat 12 Feb 2011 11:59

Post by sipe16 » Sat 12 Feb 2011 12:27

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();
    }
}

sipe16
Posts: 8
Joined: Sat 12 Feb 2011 11:59

Post by sipe16 » Sat 12 Feb 2011 13:25

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.

StanislavK
Devart Team
Posts: 1710
Joined: Thu 03 Dec 2009 10:48

Post by StanislavK » Mon 14 Feb 2011 15:12

Glad to see that the problem was resolved.

Post Reply