- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试动态转换这种类型的表达式:
myDbSet.Select(x => new MyClass
{
IsSelected = x.ChildList.Any()
})
进入:
myDbSet.Select(x => new
{
Item = x
IsSelected = x.ChildList.Any()
})
我会编写一个扩展方法,将采用强类型版本并转换为匿名版本,然后创建一个新表达式以执行如下操作:
myDbSet.Select(anonymousTransformedExpression).ToList().
.Select(newGeneratedExpression)
我希望这个 newGeneratedExpression 是:
myDbSet.Select(x => new
{
x.Item.IsSelected = x.IsSelected
return x.Item;
})
所以基本上将返回转换回强类型但应用了“IsSelected”值。
问题是我真的找不到如何做的起点..
编辑
好吧,我意识到这个问题不是很清楚,到目前为止,我已经离解决一个主要问题更近了一点。这是我得到的:
public static IEnumerable<TModel> SelectWithUnmapped<TModel> (this IQueryable<TModel> source, Expression<Func<TModel, object>> assigner) where TModel : class, new()
{
var anonymousType = typeof(AnonymousType<TModel>);
var expression = Expression.New(anonymousType);
var parameter = Expression.Parameter(typeof(TModel), "x");
//this part is hard coded to only take binding at position 0.. eventually will become dynamic
var originalBinding = ((MemberAssignment) ((MemberInitExpression) assigner.Body).Bindings[0]);
var originalExpression = originalBinding.Expression;
Expression conversion = Expression.Convert(originalExpression, typeof(object));
var bindings = new[]
{
Expression.Bind(anonymousType.GetProperty("Item"), parameter),
//this is hardcoded test
Expression.Bind(anonymousType.GetProperty("Property1"), conversion)
};
var body = Expression.MemberInit(expression, bindings);
var lambda = Expression.Lambda<Func<TModel, AnonymousType<TModel>>>(body, parameter);
var test = source.Select(lambda).ToList();
return source;
}
class AnonymousType<TModel>
{
public TModel Item { get; set; }
public object Property1 { get; set; }
public object Property2 { get; set; }
public object Property3 { get; set; }
public object Property4 { get; set; }
public object Property5 { get; set; }
public object Property6 { get; set; }
public object Property7 { get; set; }
public object Property8 { get; set; }
public object Property9 { get; set; }
public object Property10 { get; set; }
public object Property11 { get; set; }
public object Property12 { get; set; }
public object Property13 { get; set; }
public object Property14 { get; set; }
public object Property15 { get; set; }
public object Property16 { get; set; }
public object Property17 { get; set; }
public object Property18 { get; set; }
public object Property19 { get; set; }
public object Property20 { get; set; }
}
}
当我尝试分配测试时,出现以下错误:参数“x”未绑定(bind)到指定的 LINQ to Entities 查询表达式中。
这是由于我的第二次绑定(bind)使用了原始表达式的绑定(bind)表达式。但是两者都使用相同的参数名称“x”。我如何才能确保我的新绑定(bind)确实知道 x 是来自新表达式的参数?
基本上到目前为止,我正在尝试接受一个看起来像这样的表达式:
x => new Test
{
PropertyTest = x.Blah.Count()
}
进入:
x => new AnonymousType<Test>(){
Item = x,
Property1 = x.Blah.Count()
}
最佳答案
我终于写完了。我想这只是需要耐心和反复试验。帮助任何想做同样事情的人。我不得不将自己限制在一定的属性(property)数量上……可以轻松添加。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
public static class IQueryableExtensions
{
public static IEnumerable<TModel> SelectAndAssign<TModel>(this IQueryable<TModel> source, Expression<Func<TModel, object>> assigner) where TModel : class, new()
{
//get typed body of original expression
var originalBody = (MemberInitExpression)assigner.Body;
//list to store the new bindings we're creating for new expression
var newExpressionBindings = new List<MemberBinding>();
var newExpressionReturnType = typeof(AnonymousType<TModel>);
//new param
var parameter = Expression.Parameter(typeof(TModel), "x");
//base binding
newExpressionBindings.Add(Expression.Bind(newExpressionReturnType.GetProperty("Item"), parameter));
//go through all the original expression's bindings
for (var i = 0; i < originalBody.Bindings.Count; i++)
{
var originalBinding = (MemberAssignment)originalBody.Bindings[i];
var originalExpression = originalBinding.Expression;
var memberType = originalBinding.Expression.Type;
//create delegate based on the member type
var originalLambdaDelegate = typeof(Func<,>).MakeGenericType(typeof(TModel), memberType);
//create lambda from that delegate
var originalLambda = Expression.Lambda(originalLambdaDelegate, originalExpression, assigner.Parameters[0]);
//create a AnonymousVar<MemberType> from the type of the member ( to please EF unable to assign bool to object directly )
//start with getting the generic type
var genericMemberType = typeof(AnonymousVar<>).MakeGenericType(memberType);
//then create teh delegate
var genericMemberTypeDelegate = typeof(Func<>).MakeGenericType(genericMemberType);
//Now create an expression with a binding for that object to assign its Property ( strongly typed now from the generic declaration )
var genericInstantiationExpression = Expression.New(genericMemberType);
//the binding.. using the original expression expression
var genericInstantiationBinding = Expression.Bind(genericMemberType.GetProperty("Property"), originalLambda.Body);
// create the body
var genericInstantiationBody = Expression.MemberInit(genericInstantiationExpression, genericInstantiationBinding);
//now we need to recreate a lambda for this
var newBindingExpression = Expression.Lambda(genericMemberTypeDelegate, genericInstantiationBody);
//Create the binding and add it to the new expression bindings
newExpressionBindings.Add(Expression.Bind(newExpressionReturnType.GetProperty("Property" + (i + 1)), newBindingExpression.Body));
}
//start creating the new expression
var expression = Expression.New(newExpressionReturnType);
//create new expression body with bindings
var body = Expression.MemberInit(expression, newExpressionBindings);
//The actual new expression lambda
var newLambda = Expression.Lambda<Func<TModel, AnonymousType<TModel>>>(body, parameter);
// replace old lambda param with new one
var replacer = new ParameterReplacer(assigner.Parameters[0], newLambda.Parameters[0]); // replace old lambda param with new
//new lambda with fixed params
newLambda = Expression.Lambda<Func<TModel, AnonymousType<TModel>>>(replacer.Visit(newLambda.Body), newLambda.Parameters[0]);
//now that we have all we need form the server, we materialize the list
var materialized = source.Select(newLambda).ToList();
//typed return parameter
var typedReturnParameter = Expression.Parameter(typeof(AnonymousType<TModel>), "x");
//Lets assign all those custom properties back into the original object type
var expressionLines = new List<Expression>();
for (var i = 0; i < originalBody.Bindings.Count; i++)
{
var originalBinding = (MemberAssignment)originalBody.Bindings[i];
var itemPropertyExpression = Expression.Property(typedReturnParameter, "Item");
var bindingPropertyExpression = Expression.Property(itemPropertyExpression, originalBinding.Member.Name);
var memberType = originalBinding.Expression.Type;
var valuePropertyExpression = Expression.Convert(Expression.Property(typedReturnParameter, "Property" + (i + 1)), typeof(AnonymousVar<>).MakeGenericType(memberType));
var memberValuePropertyExpression = Expression.Property(valuePropertyExpression, "Property");
var equalExpression = Expression.Assign(bindingPropertyExpression, memberValuePropertyExpression);
expressionLines.Add(equalExpression);
}
var returnTarget = Expression.Label(typeof(TModel));
expressionLines.Add(Expression.Return(returnTarget, Expression.Property(typedReturnParameter, "Item")));
expressionLines.Add(Expression.Label(returnTarget, Expression.Constant(null, typeof(TModel))));
var finalExpression = Expression.Block(expressionLines);
var typedReturnLambda = Expression.Lambda<Func<AnonymousType<TModel>, TModel>>(finalExpression, typedReturnParameter).Compile();
return materialized.Select(typedReturnLambda);
}
class AnonymousVar<TModel>
{
public TModel Property { get; set; }
}
class AnonymousType<TModel>
{
public TModel Item { get; set; }
public object Property1 { get; set; }
public object Property2 { get; set; }
public object Property3 { get; set; }
public object Property4 { get; set; }
public object Property5 { get; set; }
public object Property6 { get; set; }
public object Property7 { get; set; }
public object Property8 { get; set; }
public object Property9 { get; set; }
public object Property10 { get; set; }
public object Property11 { get; set; }
public object Property12 { get; set; }
public object Property13 { get; set; }
public object Property14 { get; set; }
public object Property15 { get; set; }
public object Property16 { get; set; }
public object Property17 { get; set; }
public object Property18 { get; set; }
public object Property19 { get; set; }
public object Property20 { get; set; }
}
class ParameterReplacer : ExpressionVisitor
{
private ParameterExpression from;
private ParameterExpression to;
public ParameterReplacer(ParameterExpression from, ParameterExpression to)
{
this.from = from;
this.to = to;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return base.VisitParameter(node == this.from ? this.to : node);
}
}
}
关于c# - 将强类型表达式转换为匿名类型返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39779325/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!