public class Base_UserTestDTO : Base_User
{
public string DepartmentName { get; set; }
}
var db = DbFactory.GetRepository();
Expression<Func<Base_User, Base_Department, Base_UserTestDTO>> select = (a, b) => new Base_UserTestDTO
{
DepartmentName = b.Name
};
select = select.BuildExtendSelectExpre();
var q = from a in db.GetIQueryable<Base_User>().AsExpandable()
join b in db.GetIQueryable<Base_Department>() on a.DepartmentId equals b.Id into ab
from b in ab.DefaultIfEmpty()
select @select.Invoke(a, b);
var where = LinqHelper.True<Base_UserTestDTO>();
where = where.And(x => x.UserName == "Admin");
var list = q.Where(where).ToList();
public static Expression<Func<TBase, T1, TResult>> BuildExtendSelectExpre<TBase, T1, TResult>(this Expression<Func<TBase, T1, TResult>> expression)
{
return GetExtendSelectExpre<TBase, TResult, Func<TBase, T1, TResult>>(expression);
}
private static Expression<TDelegate> GetExtendSelectExpre<TBase, TResult, TDelegate>(Expression<TDelegate> expression)
{
NewExpression newBody = Expression.New(typeof(TResult));
MemberInitExpression oldExpression = (MemberInitExpression)expression.Body;
ParameterExpression[] oldParamters = expression.Parameters.ToArray();
List<string> existsProperties = new List<string>();
oldExpression.Bindings.ToList().ForEach(aBinding =>
{
existsProperties.Add(aBinding.Member.Name);
});
List<MemberBinding> newBindings = new List<MemberBinding>();
typeof(TBase).GetProperties().Where(x => !existsProperties.Contains(x.Name)).ToList().ForEach(aProperty =>
{
if (typeof(TResult).GetMembers().Any(x => x.Name == aProperty.Name))
{
MemberBinding newMemberBinding = null;
var valueExpre = Expression.Property(oldParamters[0], aProperty.Name);
if (typeof(TBase).IsAssignableFrom(typeof(TResult)))
{
newMemberBinding = Expression.Bind(aProperty, valueExpre);
}
else
{
newMemberBinding = Expression.Bind(typeof(TResult).GetProperty(aProperty.Name), valueExpre);
}
newBindings.Add(newMemberBinding);
}
});
newBindings.AddRange(oldExpression.Bindings);
var body = Expression.MemberInit(newBody, newBindings.ToArray());
var resExpression = Expression.Lambda<TDelegate>(body, oldParamters);
return resExpression;
}
public static class LinqHelper
{
public static Expression<Func<T,bool>> True<T>()
{
return x => true;
}
public static Expression<Func<T, bool>> False<T>()
{
return x => false;
}
}