我需要重用可用的表达式:
Expression<Func<Picture, int>> selector = o => o.EntityId;
Run Code Online (Sandbox Code Playgroud)
并构建Where的表达式:
Expression<Func<Picture, bool>> filter = w => w.EntityId > 5;
Run Code Online (Sandbox Code Playgroud)
我怎样才能构建这样的表达式?
接下来的操作不会在客户端执行,对吗?
var collection = _dbContext.Pictures.Where(filter).ToList();
Run Code Online (Sandbox Code Playgroud) 我试图创建一个Expression将调用特定的泛型重载方法(Enumerable.Average在我的第一个测试用例中).特定类型绑定直到运行时才知道,因此我需要使用它Reflection来查找和创建正确的泛型方法(Expression从解析的文本创建).
所以如果我在运行时知道我想找到这个特定的重载:
public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
Run Code Online (Sandbox Code Playgroud)
如何MethodInfo使用反射解决该特定问题?
到目前为止,我有以下选择声明:
MethodInfo GetMethod(Type argType, Type returnType)
{
var methods = from method in typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)
where method.Name == "Average" &&
method.ContainsGenericParameters &&
method.GetParameters().Length == 2 &&
// and some condition where method.GetParameters()[1] is a Func that returns type argType
method.ReturnType == returnType
select method;
Debug.Assert(methods.Count() == 1);
return methods.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
上面将它缩小到三个重载,但我想反映并找到需要在Func<TSource, int>哪里的特定重载argType == typeof(int) …
假设我有一个类,其中一个方法将System.Linq.Expressions.Expression作为参数,单元测试中有多少值呢?
public void IList<T> Find(Expression expression)
{
return someCollection.Where(expression).ToList();
}
Run Code Online (Sandbox Code Playgroud)
单元测试或嘲笑这些方法对我来说是一种令人费解的经历,现在我不得不怀疑它是否只是不值得.
我如何使用一些任意表达式对此方法进行单元测试
List<Animal> = myAnimalRepository.Find(x => x.Species == "Cat");
Run Code Online (Sandbox Code Playgroud) 我想动态生成一个linq.expressions.expression语句,我可以将其用作过滤器.
这是一个示例Linq查询,我想将其转换为Expression:
ctx.customer.where(c=>ctx.Invoice.Any(i=>i.customerId == c.id));
Run Code Online (Sandbox Code Playgroud)
这是我的尝试
using System.Linq.Expressions;
var c = Expression.parameter(typeof(Customer),"c");
var i = Expression.parameter(typeof(Invoice),"i");
var rightPart= Expression.Equal(
Expression.propertyorField(i,"customerId"), Expression.propertyorfield(c,"id")
Run Code Online (Sandbox Code Playgroud)
请协助.
我想使用LINQ将sting字段与字符串数组进行比较,我已经编写了下面的扩展方法进行比较,但它无法正常工作.
public static bool Contains(this string source, string[] keys)
{
foreach (var item in keys)
{
if (source.Contains(item))
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是我的疑问:
string[] keys = key.Split('+');
var pages = context.Pages.Where(x => x.Title.Contains(keys));
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
LINQ to Entities无法识别方法'Boolean Contains(System.String,System.String [])'方法,并且此方法无法转换为商店表达式.
好吧,我有两个表达方式 X , Y
如果flag为true,那么y有一个表达式
我需要一个 List<mylist> v = list.where(x).where(y).ToList();
在这种情况下,如果y表达式为null,则会抛出异常,
我知道在构建查询之前我可以检查null,但是在一个巨大的查询中,这可能是一场噩梦.
那么在执行表达式时是否有任何方法或值来告诉表达式被忽略?
我的代码库中有一些相当复杂的实体框架查询,我决定将逻辑集中到模型中.基本上,描绘了一堆控制器,它们在表达式树中有大量查询和大量重复代码.因此,我取出了部分表达树并将它们移动到模型中,从而减少了重复次数.
例如,假设我经常需要获取名为Entity的模型,这些模型处于Not Deleted状态.在我的实体模型上,我有:
public static Func<Entity, bool> IsNotDeleted = e =>
e.Versions != null ?
e.Versions.OrderByDescending(v => v.VersionDate).FirstOrDefault() != null ?
e.Versions.OrderByDescending(v => v.VersionDate).First().ActivityType != VersionActivityType.Delete :
false :
false;
Run Code Online (Sandbox Code Playgroud)
(这是较小的示例之一,主要是在尝试检查数据之前检查有效数据.)
使用它看起来像:
var entities = EntityRepository.Entities.Where(Entity.IsNotDeleted).Where(...
Run Code Online (Sandbox Code Playgroud)
但是我发现,虽然有时候我想这是不会被删除的记录,其他时间我想要的记录被删除.要做到这一点,有没有办法从消费代码中反转逻辑?概念上类似于此的东西(显然不起作用):
var entities = EntityRepository.Entities.Where(!Entity.IsDeleted).Where(...
Run Code Online (Sandbox Code Playgroud)
我宁愿不在Func<>物体上有两个,一个用于IsDeleted,另一个IsNotDeleted几乎相同.的Func<>回报bool,是否有语法把一个在当它调用它的逆.Where()条款?
我想使用LINQ表达式设置私有字段。我有以下代码:
//parameter "target", the object on which to set the field `field`
ParameterExpression targetExp = Expression.Parameter(typeof(object), "target");
//parameter "value" the value to be set in the `field` on "target"
ParameterExpression valueExp = Expression.Parameter(typeof(object), "value");
//cast the target from object to its correct type
Expression castTartgetExp = Expression.Convert(targetExp, type);
//cast the value to its correct type
Expression castValueExp = Expression.Convert(valueExp, field.FieldType);
//the field `field` on "target"
MemberExpression fieldExp = Expression.Field(castTartgetExp, field);
//assign the "value" to the `field`
BinaryExpression assignExp = Expression.Assign(fieldExp, …Run Code Online (Sandbox Code Playgroud) 我在.net核心写mvc应用程序,我有本地化问题,我不知道如何将IViewLocalizer添加到我的网格视图.这是我的代码:
@using NonFactors.Mvc.Grid;
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@model IEnumerable<WeegreeEmployeeFormsCore.Models.Employee>
@(Html
.Grid(Model)
.Build(columns =>
{
columns.Add(model => model.Name).Titled(Localizer["Name"]).Sortable(true).Filterable(true);
columns.Add(model => model.Surname).Titled(Localizer["Surname"]).Sortable(true).Filterable(true);
columns.Add(model => model.EmploymentDate).Titled(Localizer["Hired"]).Sortable(true).Filterable(true);
columns.Add(model => model.Country).Titled(Localizer["Country"]).Filterable(true).Sortable(true).Filterable(true);
columns.Add(model => model.EmploymentForm).Titled(Localizer["EmploymentForm"]).Filterable(true);
columns.Add(model => $"<a href=\"{Url.Action("Edit", "Form")}/{model.EmployeeId}\">{Localizer["Edit"]}</a>").Encoded(false);
columns.Add(model => $"<a href=\"{Url.Action("Details", "Form")}/{model.EmployeeId}\">Details</a>").Encoded(false);
})
.Pageable(pager =>
{
pager.PagesToDisplay = 10;
pager.CurrentPage = 1;
pager.RowsPerPage = 10;
})
.Sortable()
.Empty("No data found")
)
Run Code Online (Sandbox Code Playgroud)
当我{}用来插入内部表达model.EmployeeId它工作 - 链接工作,但当我想使用Localizer来获取题字Edit/Edytuj/??????? etc.而不是我在我看来得到这个:
Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString
c# linq linq-expressions asp.net-core asp.net-core-localization
所以我有点厌倦了一遍又一遍地重写相同的查询.
repo.Query().Where(stuff => stuff.Timestamp >= minTime && stuff.Timestamp <= maxTime && ...);
Run Code Online (Sandbox Code Playgroud)
我以为我应该IQueryable使用一个名为的方法进行扩展IsInDateTimeRange,并像这样使用它
repo.Query().IsInDateTimeRange(stuff => stuff.Timestamp, minTime, maxTime) ...
Run Code Online (Sandbox Code Playgroud)
这将是非常容易的IEnumerable,只有一个Func<T, DateTime>和两个DateTime,但是对于IQueryable我需要采取一个Expression,我不知道如何使用它.
这是我的尝试,但似乎没有奏效.
public static IQueryable<TValue> IsInDateTimeRange<TValue>(
this IQueryable<TValue> self,
Expression<Func<TValue, DateTime>> getMember,
DateTime minTime,
DateTime maxTime)
{
return self.Where(value => minTime >= getMember(value) && maxTime <= getMember(value));
}
Run Code Online (Sandbox Code Playgroud) c# ×10
linq-expressions ×10
linq ×6
reflection ×2
.net ×1
.net-3.5 ×1
asp.net-core ×1
ef-core-2.2 ×1
func ×1
generics ×1
iqueryable ×1
lambda ×1
mocking ×1
unit-testing ×1