【问题标题】:How to write Linq To Entities with multiple optional parameters如何使用多个可选参数编​​写 Linq To Entity
【发布时间】:2018-12-10 01:06:54
【问题描述】:

我有一个名为 Items(Name,Description) 的表

用户可以根据名称、描述或两者来搜索项目。 (实际的表有大约 15 个可以搜索的字段,但在这个例子中,只保留了两个)。

这将搜索名称和描述。但我需要它是一个,另一个或两者兼而有之。

var source = this.DbContext.Items;

IQueryable<Item> items = source.Where(a => a.Name.Contains(item.Name));

items = items.Where(a => a.Description.Contains(item.Description));

return items.ToList();

这是我想出的最好的,但第二行似乎有点时髦。

internal List<Item> Search(Item item)
{
    var source = this.DbContext.Items;
    IQueryable<Item> items = source.Where(a=> a == a);

    if(!string.IsNullOrWhiteSpace(item.Name)) items = items.Where(a => a.Name.Contains(item.Name));

    if(!string.IsNullOrWhiteSpace(item.Description)) items = items.Where(a => a.Description.Contains(item.Description));

    return items.ToList();          
}       

【问题讨论】:

  • 究竟在寻找什么?摆脱这条线IQueryable&lt;Item&gt; items = source.Where(a=&gt; a == a);
  • 是的,我想去掉那一行。

标签: c# entity-framework linq-to-entities entity-framework-core


【解决方案1】:

如果你想去掉这个sn-p中的第二行:

var source = this.DbContext.Items;
IQueryable<Item> items = source.Where(a=> a == a);

只需将它们替换为:

// your Linq To Entities query is already an IQueryable<T>
var items = from item in this.DbContext.Items
            select item;

或者更简单的去掉var关键字:

// There is an implicit conversion between DbSet<T> and IQueryable<T> 
// but you gain from it only if you remove the var keyword and not use the type inference
IQueryable<Item> items = this.DbContext.Items;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多