Question

I'm trying to create a Linq statement that queries both columns that exist on my entity as properties and those that don't but exist as columns in the database for the entity.

For example, I have a collection of Book entities. Each Book has an ID and Title property and a matching column in the database. But, lets say the table for Book also contains a column field for Author and my Book entity doesn't have this.

A normal query involving the ID and the Title might look like this:

Books.Where(b=>b.ID == 123 && b.Title == "Title")

But, I want to also dynamically add the equivalent of " AND Author = 'Name' " to the above query as well. The Author property doesn't exist on the Book object.

The extra fields and the values they should contain will actually be available in a Dictionary. So I will need to dynamically add multiple AND [FieldName] = '[Value]' conditions to the query.

It might help explain why I would need this to know that I'm using Azure Table Storage and I have overridden the serialize that turns a Book entity into the XML stored in Azure.

Edit -

I've tried using the Dynamic Linq library but it does not work.

Books.Where(b=>b.ID == 123 && b.Title == "Title").Where("Author = @0", "SomeName").ToList();

Throws: System.Linq.Dynamic.ParseException: No property or field 'Author' exists in type 'Book'.

Also,

I know using Books.AddQueryOption("$filter","Author eq 'SomeName'") works when used by itself. But I have no idea how to use AddQueryOption along with an existing Where statement.

Was it helpful?

Solution 2

This is not possible with LINQ

OTHER TIPS

Without adding Author to Book, you would either have to pass another object with Author on it:

var x = new { Author="SomeName" };  
    Books.Where(b=>b.Id == 1 && b.Title == "Alpha").Where("@1.Author == @0", "SomeName", x);

Or inherit from Book and add an Author property just for this purpose:

public class BookEx : Book {
    public string Author { get; set; }
}

Books.Cast<BookEx>().Where(b=>b.Id == 1 && b.Title== "Alpha").Where("Author == @0", "SomeName");

Try the following code:

var result = _tofiObjectList.Where(o => o.GetType() == mainObjType)
    .AsQueryable().Cast(relation.MainObject.EntityType).Where(relation.MainObject.Filter);

This is an extension method for IQueryable type:

public static IQueryable Cast(this IQueryable source, string type)
{
    switch (type)
    {
        case "TofiDataCollection.Service.TofiEntity.Obj":
            return source.Cast<Obj>();
    }
    return source;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top