How to Create a Linq Query with Multiple Conditional Where Clauses - linq

I have a linq query with multiple conditional where clauses. The query returns all data in the table when there is no filter in the where clause. How to make the linq query returns 0 record in the first time when there is no filter in the where clause? See my code below:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Http;
using API.Models;
using System.Linq.Expressions;
namespace API.Controllers
{
//api code starts here
public class MYTABLEController : ApiController
{
private DataModel db = new DataModel();
//GET /MYTABLE
public List<MYTABLE> Get(string filter1 = null,string filter2=null)
{
IQueryable<MYTABLE> qry = db.MYTABLE.AsQueryable();
var searchPredicate = PredicateBuilder.False<MYTABLE>();
if (!string.IsNullOrWhiteSpace(filter1))
{
searchPredicate = searchPredicate.And(a => a.COLUMN1==(filter1);
}
if (!string.IsNullOrWhiteSpace(filter2))
{
searchPredicate = searchPredicate.And(a => a.COLUMN2==(filter2);
}
return qry.Where(searchPredicate).ToList();
}
//PredicateBuilder https://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/
public static class PredicateBuilder
{
/// <summary>
/// Creates a predicate that evaluates to true.
/// </summary>
public static Expression<Func<T, bool>> True<T>() { return param => true; }
/// <summary>
/// Creates a predicate that evaluates to false.
/// </summary>
public static Expression<Func<T, bool>> False<T>() { return param => false; }
/// <summary>
/// Creates a predicate expression from the specified lambda expression.
/// </summary>
public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }
/// <summary>
/// Combines the first predicate with the second using the logical "and".
/// </summary>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
/// <summary>
/// Combines the first predicate with the second using the logical "or".
/// </summary>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
/// <summary>
/// Negates the predicate.
/// </summary>
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
{
var negated = Expression.Not(expression.Body);
return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
}
/// <summary>
/// Combines the first expression with the second using the specified merge function.
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// zip parameters (map from parameters of second to parameters of first)
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with the parameters in the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// create a merged lambda expression with parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
class ParameterRebinder : ExpressionVisitor
{
readonly Dictionary<ParameterExpression, ParameterExpression> map;
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}

Update this method like this:
public List<MYTABLE> Get(string filter1 = null,string filter2=null)
{
if(string.IsNullOrWhiteSpace(filter1) && string.IsNullOrWhiteSpace(filter2))
return new List<MYTABLE>();
IQueryable<MYTABLE> qry = db.MYTABLE.AsQueryable();
var searchPredicate = PredicateBuilder.False<MYTABLE>();
if (!string.IsNullOrWhiteSpace(filter1))
{
searchPredicate = searchPredicate.And(a => a.COLUMN1==(filter1);
}
if (!string.IsNullOrWhiteSpace(filter2))
{
searchPredicate = searchPredicate.And(a => a.COLUMN2==(filter2);
}
return qry.Where(searchPredicate).ToList();
}

First, I'd use a predicate builder for this. For example this one.
That would turn your code into:
IQyeryable<MyTable> qry = db.myTable;
var predicate = PredicateBuilder.True<MyTable>();
if (!string.IsNullOrWhiteSpace(filter1))
{
predicate = predicate.And(a => a.column1.Contains(filter1));
}
if (!string.IsNullOrWhiteSpace(filter2))
{
predicate = predicate.And(a => a.column2.Contains(filter2));
}
...
qry = qry.Where(predicate);
Now it's easy to check if any predicates were added. If not, predicate is nothing but a => true, which means that its body is just a ConstantExpression (value: true). You can add this check just above the last line:
if (predicate.Body is ConstantExpression)
{
predicate = PredicateBuilder.False<MyTable>();
}
(Of course provided that you don't replace predicate by another predicate, another constant expression, but I guess that wouldn't make much sense).

You can create an extension method:
public static IQueryable<T> WhereIf<T>(
this IQueryable<T> source, bool condition,
Expression<Func<T, bool>> predicate)
{
return condition ? source.Where(predicate) : source;
}
And use it in a following fashion:
using static System.String;
...
public List<MYTABLE> Get(string filter1 = null,string filter2=null)
{
return db.MYTABLE
.WhereIf(!IsNullOrEmpty(filter1), y => y.COLUMN1 == filter1)
.WhereIf(!IsNullOrEmpty(filter2), y => y.COLUMN2 == filter2)
.ToList();
}

Related

Convert Expression<Func<T, bool>> to another Predicate Expression Expression<Func<U, bool>>

I want to convert One predicate Expression(Expression<Func<Item, bool>>) to another Predicate Expression (Expression<Func<ItemEntity, bool>>) but after converting I am not able to query through LINQ.
I Already try this and this approach but nothing work properly
can anyone tells me how to do it properly, My approach for this problems.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Reflection;
public class ItemEntity {
public int ItemId {set;get;}
public int ItemParentId {set;get;}
public int ItemName {set;get;}
}
public class Item {
public int Id{ set;get;}
public int ParentId{set;get;}
public int Name {set;get;}
}
public class Program
{
public static Item Convert(ItemEntity itemChild)
{
return new Item()
{
Id = itemChild.ItemId,
ParentId = itemChild.ItemParentId,
Name = itemChild.ItemName
};
}
public async Task<IList<ItemEntity>> SelectAsync(Expression<Func<ItemEntity, bool>> predicate)
{
// using Microsoft.EntityFrameworkCore;
// private readonly DbContext _context; // Injected globally by using Service.AddScoped<ItemContext>();
// return await _context.Set<ItemEntity>().AsNoTracking().Where(predicate).ToListAsync();
return await Task.Run(() => new List<ItemEntity>()); // actually return the result with matching predicate
}
public async Task<List<Item>> GetItems(Expression<Func<Item, bool>> expression)
{
MethodInfo convertMethod = ((Func<ItemEntity, Item>)Convert).Method;
var p = Expression.Parameter(typeof(ItemEntity));
var converted = Expression.Lambda<Func<ItemEntity, bool>>(
Expression.Invoke(expression, Expression.Convert(p, typeof(Item), convertMethod)), p);
IList<ItemEntity> res = await SelectAsync(converted);
var t = res.Select(x => Convert(x)).ToList();
return t;
}
public static void Main()
{
Program pr = new Program();
Func<Expression<Func<Item, bool>>, Task<List<Item>>> getItem = pr.GetItems;
var res = getItem.Invoke(x => x.Id.Equals(1));
Console.WriteLine("Hello World");
}
}
but I am getting error
The LINQ expression 'DbSet()\r\n .Where(i => ((Item)i).Id.Equals(__Id_0))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
I don't able to understand it properly, as per my understanding I am using ToList() for client evaluation, but and also provide method to convert ItemEntity to Item.
I any other way to create fresh Expression Tree based on ItemEntity and then query on DBSet?
Any Help is appreciated
version used:
dot-net 5.0
Microsoft.EntityFrameworkCore 5.0.6
EntityFramework 6.4.4
Database SQL Server
Try the following approach. Main idea to use filter exactly on the projected DTO before materialization.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
public class ItemEntity
{
public int ItemId { set; get; }
public int ItemParentId { set; get; }
public int ItemName { set; get; }
}
public class Item
{
public int Id { set; get; }
public int ParentId { set; get; }
public int Name { set; get; }
}
public class Program
{
public static Expression<Func<ItemEntity, Item>> ToItem()
{
return itemChild => new Item
{
Id = itemChild.ItemId,
ParentId = itemChild.ItemParentId,
Name = itemChild.ItemName
};
}
public Task<IList<Item>> SelectAsync(Expression<Func<Item, bool>> predicate)
{
return _context.Set<ItemEntity>()
.AsNoTracking()
.Select(ToItem())
.Where(predicate)
.ToListAsync();
//return Task.Run(() => new List<ItemEntity>().AsQueryable().Select(ToItem()).Where(predicate).ToList());
}
public async Task<IList<Item>> GetItems(Expression<Func<Item, bool>> expression)
{
var res = await SelectAsync(expression);
return res;
}
public static void Main()
{
var pr = new Program();
var res = pr.GetItems(x => x.Id == 1);
Console.WriteLine("Hello World");
}
}

Convert expression tree types

I've searched high an low of SO to find a solution for my problem.
I've found several answers for when it comes to simple expressions like
var exp1 Expression<Func<T, bool>> x => x.Name == "MyName"
But I'm having trouble when the expressions are like:
var exp1 Expression<Func<T, bool>> x => x.Category.Name == "Coupe"
For the simple ones, I am able to convert any expression from one type (T) to another (TT), I need to do it also in the other cases, more complex...
Anyone who can help with some pointers? Here is what I've got so far:
private class CustomVisitor<T> : ExpressionVisitor
{
private readonly ParameterExpression mParameter;
public CustomVisitor(ParameterExpression parameter)
{
mParameter = parameter;
}
//this method replaces original parameter with given in constructor
protected override Expression VisitParameter(ParameterExpression node)
{
return mParameter;
}
private int counter = 0;
/// <summary>
/// Visits the children of the <see cref="T:System.Linq.Expressions.MemberExpression" />.
/// </summary>
/// <param name="node">The expression to visit.</param>
/// <returns>
/// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
protected override Expression VisitMember(MemberExpression node)
{
counter++;
System.Diagnostics.Debug.WriteLine("{0} - {1}", node.ToString(), counter);
try
{
//only properties are allowed if you use fields then you need to extend
// this method to handle them
if (node.Member.MemberType != System.Reflection.MemberTypes.Property)
throw new NotImplementedException();
//name of a member referenced in original expression in your
//sample Id in mine Prop
var memberName = node.Member.Name;
//find property on type T (=PersonData) by name
var otherMember = typeof(T).GetProperty(memberName);
//visit left side of this expression p.Id this would be p
var inner = Visit(node.Expression);
return Expression.Property(inner, otherMember);
}
catch (Exception ex)
{
return null;
}
}
}
Utility method:
public static Expression<Func<TDestin, T>> ConvertTypesInExpression<TSource, TDestin, T>(Expression<Func<TSource, T>> source)
{
var param = Expression.Parameter(typeof(TDestin));
var body = new CustomVisitor<TDestin>(param).Visit(source.Body);
Expression<Func<TDestin, T>> lambda = Expression.Lambda<Func<TDestin, T>>(body, param);
return lambda;
}
And it's being used like this:
var changedFilter = ConvertTypesInExpression<ClientNotificationRuleDto, ClientNotificationRule, bool>(filterExpression);
So if anyone can help with some ideias or pointers, that would be great!
Analyze this test:
class Replaced
{
public Inner Inner { get; set; }
}
class Inner
{
public string Name { get; set; }
}
class Replacing
{
public Inner Inner { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var parameter = Expression.Parameter(typeof(Replacing));
var visitor = new CustomVisitor(parameter);
Expression<Func<Replaced, bool>> expression = x => x.Inner.Name == "ss";
var resultExpression = (Expression<Func<Replacing, bool>>)visitor.Visit(expression);
var function = resultExpression.Compile();
var result = function(new Replacing
{
Inner = new Inner
{
Name = "ss"
}
});
Assert.IsTrue(result);
}
}
internal class CustomVisitor : ExpressionVisitor
{
private readonly ParameterExpression mParameter;
private int counter = 0;
public CustomVisitor(ParameterExpression parameter)
{
mParameter = parameter;
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
return Expression.Lambda(
Visit(node.Body),
node.Parameters.Select(x => (ParameterExpression)Visit(x)).ToArray());
//or simpler but less generic
//return Expression.Lambda(Visit(node.Body), mParameter);
}
//this method will be called twice first for Name and then for Inner
protected override Expression VisitMember(MemberExpression node)
{
counter++;
System.Diagnostics.Debug.WriteLine("{0} - {1}", node.ToString(), counter);
if (node.Member.MemberType != System.Reflection.MemberTypes.Property)
throw new NotImplementedException();
var memberName = node.Member.Name;
var inner = Visit(node.Expression);
var otherMember = inner.Type.GetProperty(memberName);
return Expression.Property(inner, otherMember);
}
protected override Expression VisitParameter(ParameterExpression node)
{
return mParameter;
}
}
Note that visit member is called twice and must react accordingly for both calls. Also you need to override the lambda creation as it would fail in parameter replacement.
PS: Never catch base class Exception its just bad practice and the panic return null on exception is just wrong.
With the precious help from #Rafal and insights from this, I managed to achieve a solution for my needs
public static class EXpressionTreeTools
{
#region ConvertTypesInExpression
/// <summary>
/// Converts the types in the expression.
/// </summary>
/// <typeparam name="TSource">The source type (the "replacee").</typeparam>
/// <typeparam name="TDestin">The destiny type (the replacer).</typeparam>
/// <typeparam name="T">The type of the result fo the expression evaluation</typeparam>
/// <param name="source">The source expression.</param>
/// <returns></returns>
public static Expression<Func<TDestin, T>> ConvertTypesInExpression<TSource, TDestin, T>(Expression<Func<TSource, T>> source)
{
var parameter = Expression.Parameter(typeof(TDestin));
var visitor = new CustomVisitor(parameter);
//Expression<Func<TSource, bool>> expression = x => x.Inner.Name == "ss";
Expression<Func<TDestin, T>> resultExpression = (Expression<Func<TDestin, T>>)visitor.Visit(source);
return resultExpression;
}
#endregion
#region CustomVisitor
/// <summary>
/// A custom "visitor" class to traverse expression trees
/// </summary>
/// <typeparam name="T"></typeparam>
internal class CustomVisitor : ExpressionVisitor
{
private readonly ParameterExpression mParameter;
public CustomVisitor(ParameterExpression parameter)
{
mParameter = parameter;
}
protected override Expression VisitLambda<T>(Expression<T> node)
{
return Expression.Lambda(
Visit(node.Body),
node.Parameters.Select(x => (ParameterExpression)Visit(x)).ToArray());
//or simpler but less generic
//return Expression.Lambda(Visit(node.Body), mParameter);
}
//this method will be called twice first for Name and then for Inner
protected override Expression VisitMember(MemberExpression node)
{
if (node.Member.MemberType != System.Reflection.MemberTypes.Property)
//throw new NotImplementedException();
{
Expression exp = this.Visit(node.Expression);
if (exp == null || exp is ConstantExpression) // null=static member
{
object #object = exp == null ? null : ((ConstantExpression)exp).Value;
object value = null; Type type = null;
if (node.Member is FieldInfo)
{
FieldInfo fi = (FieldInfo)node.Member;
value = fi.GetValue(#object);
type = fi.FieldType;
}
else if (node.Member is PropertyInfo)
{
PropertyInfo pi = (PropertyInfo)node.Member;
if (pi.GetIndexParameters().Length != 0)
throw new ArgumentException("cannot eliminate closure references to indexed properties");
value = pi.GetValue(#object, null);
type = pi.PropertyType;
}
return Expression.Constant(value, type);
}
else // otherwise just pass it through
{
return Expression.MakeMemberAccess(exp, node.Member);
}
}
var memberName = node.Member.Name;
var inner = Visit(node.Expression);
var otherMember = inner.Type.GetProperty(memberName);
return Expression.Property(inner, otherMember);
}
protected override Expression VisitParameter(ParameterExpression node)
{
return mParameter;
}
}
#endregion
}

Lambda expression check if null helper

I want to be able to write
MyObject.IsNull(p => p.MyObjectProperty)
I think it is achievable with expression.
I thied to implement it this way:
public static void IsNull<T>(this T root, Expression<Func<T, object>> expression)
{
if (CheckIfNull<T>(expression))
{
throw new ArgumentNullException(GetName(expression));
}
}
private static string GetName<T>(Expression<Func<T, object>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
public static bool CheckIfNull<T>(Expression<Func<T, object>> expression)
{
Expression<Func<T, object>> obj = o => expression.Compile().Invoke(o);
return obj == null;
}
But it is seams to be not working.
How can I fix that?
You have a bug:
The comparison obj == null should be obj(root) == null - of course you have to pass root as an argument to CheckIfNull.
The former comparison will always evaluate to false, since you are effectively comparing o => expression.Compile().Invoke(o) with null - they are never equal. You rather want to compare the result of the call to Invoke with null.
All my suggestions combined:
public static bool CheckIfNull<T>(this T root, Expression<Func<T, object>> expression)
{
return expression.Compile()(root) == null;
}
public static void IsNull<T>(this T root, Expression<Func<T, object>> expression)
{
if (root.CheckIfNull<T>(expression))
{
throw new ArgumentNullException(GetName(expression));
}
}
private static string GetName<T>(Expression<Func<T, object>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
Further comments:
I'm not sure ArgumentNullException is the right exception for this situation. But without knowledge about your scenario, it is hard to suggest something better. Actually:
it seems weird to write an extension method that merely throws an exception if a member is null, especially for a method named IsNull, which is why
I would rename IsNull to ThrowIfNull and rename CheckIfNull to IsNull

Filter a Collection on LINQ with Recursion

I have a collection named as MenuItemCollection and this derived form List< MenuItem >
There is a Singleton Instance of MenuItemCollection and if I simplify the fields of MenuItem:
public class MenuItem
{
int Id {set;get;}
string Title {set;get;}
MenuItemCollection ChildMenus {set;get;}
}
I need to use a filter method on this collection. For example, I'd like to filter the collection for one menu's Id.
Here is a sample MenuItemCollection:
1-Home
2-User Menu
4-Update Info
5-Delete Account
3-News
6-Archived News
As you can see there some Child menus such as number 4 or number 6
I normally use below to filter:
public List<MenuItem> Filter(MenuItemFilterArgs args)
{
List<MenuItem> Result = new List<MenuItem>();
IQueryable<MenuItem> QueryableTemp = this.AsQueryable();
return (from item in QueryableTemp
orderby item.Ordering descending
select item).ToList<MenuItem>();
}
And calling this method as:
var FilteredMenus = MenuItemCollection.GetInstance.Filter(new MenuItemFilterArgs { Id = 5 });
Since number 5 is in an inner collection under number 2 menuitem, the result returns as 0. It cannot be found.
How is it possible to run the filter recursively through inner MenuItemCollections? Could you write a code sample?
PS: If you must know why I'm using a singleton instance; my idea was
to retrieve the menus from database and keep it as an object for
easier and faster usage on run-time.
Any help would be highly appreciated.
Thanks in advance
Here is a working example. The ExtensionMethods.Map method is what you need.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
var menuItems1 = MenuItemCollection.Instance.Filter(null);
var menuItems2 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Id = 5 });
var menuItems3 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Title = "News" });
var menuItems4 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Title = "News", IsTrash = true });
}
}
public class MenuItemCollection : List<MenuItem>
{
public static readonly MenuItemCollection Instance;
static MenuItemCollection()
{
Instance = GetMenuList();
}
static MenuItemCollection GetMenuList()
{
return new MenuItemCollection {
new MenuItem {Id = 1, Title = "Home"},
new MenuItem {Id = 2, Title = "User Menu", ChildMenus = new MenuItemCollection {
new MenuItem { Id = 4, Title = "Update Info"},
new MenuItem { Id = 5, Title = "Delete"}
}},
new MenuItem {Id = 3, Title = "News", ChildMenus = new MenuItemCollection {
new MenuItem { Id = 6, Title = "Archived News"},
new MenuItem { Id = 6, Title = "Trashy News", IsTrash = true}
}},
};
}
public List<MenuItem> Filter(MenuItemCriteria criteria)
{
var expression = PredicateBuilder.True<MenuItem>();
if(criteria != null)
{
if (criteria.Id.HasValue)
{
expression = expression.And(menuItem => menuItem.Id == criteria.Id);
}
if (!string.IsNullOrEmpty(criteria.Title))
{
expression = expression.And(menuItem => menuItem.Title.Contains(criteria.Title));
}
if (criteria.IsTrash.HasValue)
{
expression = expression.And(menuItem => menuItem.IsTrash == criteria.IsTrash);
}
}
Func<MenuItem, bool> searchCriteria = expression.Compile();
Func<MenuItem, IEnumerable<MenuItem>> childrenSelector = x => x.ChildMenus;
return this.Map(searchCriteria, childrenSelector).ToList();
}
}
public class MenuItemCriteria
{
public int? Id { set; get; }
public string Title { set; get; }
public bool? IsTrash { set; get; }
}
public class MenuItem
{
public int Id { set; get; }
public string Title { set; get; }
public bool IsTrash { set; get; }
public MenuItemCollection ChildMenus { set; get; }
}
public static class ExtensionMethods
{
public static IEnumerable<T> Map<T>(this IEnumerable<T> source,
Func<T, bool> selector = null,
Func<T, IEnumerable<T>> childrenSelector = null)
{
if (source == null) return new List<T>();
if (selector == null)
{
// create a default selector that selects all items
selector = x => true;
}
var list = source.Where(selector);
if (childrenSelector != null)
{
foreach (var item in source)
{
list = list.Concat(childrenSelector(item).Map(selector, childrenSelector));
}
}
return list;
}
}
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}

EF4 LINQ Include(string) alternative to hard-coded string?

Is there any alternative to this:
Organizations.Include("Assets").Where(o => o.Id == id).Single()
I would like to see something like:
Organizations.Include(o => o.Assets).Where(o => o.Id == id).Single()
to avoid the hard-coded string "Assets".
In EF 4.1, there is a built-in extension method for this.
You must have a reference to "EntityFramework" assembly (where EF 4.1 lives) in your project and use System.Data.Entity.
using System.Data.Entity;
If you want to include nested entities, you do it like this:
db.Customers.Include(c => c.Orders.Select(o => o.LineItems))
Not sure if this works for EF4.0 entities (ObjectContext based).
For Entity Framework 1.0, I created some extensions methods for doing this.
public static class EntityFrameworkIncludeExtension
{
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> src, Expression<Func<T, StructuralObject>> fetch)
{
return src.Include(CreateFetchingStrategyDescription(fetch));
}
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch)
{
return src.Include(CreateFetchingStrategyDescription(fetch));
}
public static ObjectQuery<T> Include<T, TFectchedCollection>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<TFectchedCollection>>> fetch)
{
return src.Include(CreateFetchingStrategyDescription(fetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, Object>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, RelatedEnd>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, StructuralObject>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, Object>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, RelatedEnd>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, StructuralObject>> secondFetch)
where FetchedChild : StructuralObject
{
return src.Include(CombineFetchingStrategies(fetch, secondFetch));
}
private static String CreateFetchingStrategyDescription<TFetchEntity, TFetchResult>(
Expression<Func<TFetchEntity, TFetchResult>> fetch)
{
fetch = (Expression<Func<TFetchEntity, TFetchResult>>)FixedWrappedMemberAcces.ForExpression(fetch);
if (fetch.Parameters.Count > 1)
throw new ArgumentException("CreateFetchingStrategyDescription support only " +
"one parameter in a dynamic expression!");
int dot = fetch.Body.ToString().IndexOf(".") + 1;
return fetch.Body.ToString().Remove(0, dot);
}
private static String CreateFetchingStrategyDescription<T>(Expression<Func<T, Object>> fetch)
{
return CreateFetchingStrategyDescription<T, Object>(fetch);
}
private static String CombineFetchingStrategies<T, TFetchedEntity>(
Expression<Func<T, Object>> fetch, Expression<Func<TFetchedEntity, Object>> secondFetch)
{
return CombineFetchingStrategies<T, Object, TFetchedEntity, Object>(fetch, secondFetch);
}
private static String CombineFetchingStrategies<TFetchEntity, TFetchResult, TFetchedEntity, TSecondFetchResult>(
Expression<Func<TFetchEntity, TFetchResult>> fetch, Expression<Func<TFetchedEntity, TSecondFetchResult>> secondFetch)
{
return CreateFetchingStrategyDescription<TFetchEntity, TFetchResult>(fetch) + "." +
CreateFetchingStrategyDescription<TFetchedEntity, TSecondFetchResult>(secondFetch);
}
}
Usage:
Orders.Include(o => o.Product); // generates .Include("Product")
Orders.Include(o => o.Product.Category); // generates .Include("Product.Category")
Orders.Include(o => o.History); // a 1-* reference => .Include("History")
// fetch all the orders, and in the orders collection.
// also include the user reference so: .Include("History.User")
// but because history is an collection you cant write o => o.History.User,
// there is an overload which accepts a second parameter to describe the fetching
// inside the collection.
Orders.Include(o => o.History, h => h.User);
I haven't tested this on EF4.0, but I expect it to work.
That's pretty easy to do, using Expressions :
public static class ObjectQueryExtensions
{
public static ObjectQuery<T> Include<T, TProperty>(this ObjectQuery<T> objectQuery, Expression<Func<T, TProperty>> selector)
{
MemberExpression memberExpr = selector.Body as MemberExpression;
if (memberExpr != null)
{
return objectQuery.Include(memberExpr.Member.Name);
}
throw new ArgumentException("The expression must be a MemberExpression", "selector");
}
}
You can use it exactly as in the example in your question
UPDATE
Improved version, which supports multiple chained properties :
public static class ObjectQueryExtensions
{
public static ObjectQuery<T> Include<T, TProperty>(this ObjectQuery<T> objectQuery, Expression<Func<T, TProperty>> selector)
{
string propertyPath = GetPropertyPath(selector);
return objectQuery.Include(propertyPath);
}
public static string GetPropertyPath<T, TProperty>(Expression<Func<T, TProperty>> selector)
{
StringBuilder sb = new StringBuilder();
MemberExpression memberExpr = selector.Body as MemberExpression;
while (memberExpr != null)
{
string name = memberExpr.Member.Name;
if (sb.Length > 0)
name = name + ".";
sb.Insert(0, name);
if (memberExpr.Expression is ParameterExpression)
return sb.ToString();
memberExpr = memberExpr.Expression as MemberExpression;
}
throw new ArgumentException("The expression must be a MemberExpression", "selector");
}
}
Example :
var query = X.Include(x => x.Foo.Bar.Baz) // equivalent to X.Include("Foo.Bar.Baz")
See 'Say goodbye to the hardcoded ObjectQuery(T).Include calls'.
Another solution is to retrieve entity name using EntitySet.Name.
You code will be:
var context = new DBContext();
context.Organizations.Include(context.Assets.EntitySet.Name).Where(o => o.Id == id).Single()
Good news that EF4 CTP4 currently support this feature.
Another option is to include an internal partial class inside your class using the TT template.
T4 code:
<#
region.Begin("Member Constants");
#>
public partial class <#=code.Escape(entity)#>Members
{
<#
foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
{
bool isForeignKey = entity.NavigationProperties.Any(np=>np.GetDependentProperties().Contains(edmProperty));
bool isDefaultValueDefinedInModel = (edmProperty.DefaultValue != null);
bool generateAutomaticProperty = false;
#>
public const string <#=code.Escape(edmProperty)#> = "<#=code.Escape(edmProperty)#>";
<#
}
#>
}
<#
region.End();
#>
Which will produce something like:
#region Member Constants
public partial class ContactMembers
{
public const string ID = "ID";
public const string OriginalSourceID = "OriginalSourceID";
public const string EnabledInd = "EnabledInd";
public const string EffectiveDTM = "EffectiveDTM";
public const string EndDTM = "EndDTM";
public const string EnterDTM = "EnterDTM";
public const string EnterUserID = "EnterUserID";
public const string LastChgDTM = "LastChgDTM";
public const string LastChgUserID = "LastChgUserID";
}
#endregion

Resources