【问题标题】:LINQ: how to construct an IQueryable<CustomMadeType> based on search criteria on the properties of the entity, including many-to-many-relationshipLINQ:如何根据实体属性的搜索条件(包括多对多关系)构造 IQueryable<CustomMadeType>
【发布时间】:2021-08-21 23:13:36
【问题描述】:

我努力构建并轻松找到正确的信息来定义 LINQ 表达多对多标准的正确信息,因此是问答。

请修改/改进/更正/...

基本情况:

  • .Net Entity Framework 代码优先
  • 我们使用 UnitOfWork 存储库,但这在这里并不重要
  • 我们定义了一个IQueryable&lt;MyCustomMadeEntity&gt; 查询
  • 用户通过表单提交他的搜索条件,每个条件直接匹配 MyCustomMadeEntity 的属性或与 MyCustomMadeEntity 具有多对多关系的另一个实体的属性,例如:
public class MyCustomMadeEntity : BaseEntity
{
    public string ArticleCode { get; set; }
    public string Comment { get; set; }
    public Guid? ColorId { get; set; }
    public ArticleColor Color { get; set; }

    public ICollection<ArticleStatus> ArticleStatuses { get; set; }
}

public class MyCustomMadeEntity : BaseEntity
{
    // properties
    Public LocationType LocationType { get; set; }
}

(如果 LocationType 是自定义枚举

【问题讨论】:

  • 感谢@marc_s 编辑

标签: linq many-to-many iqueryable


【解决方案1】:
  1. 构造一个基 IQueryable&lt;Entity&gt; 表示数据库源以及基表与其他表的链接(连接等)
IQueryable<CustomMadeEntity> query = _UnitOfWork. ustomMadeEntityRepository
                    .Queryable()
                    .Include(el => el.OtherEntity);
query = PerformAdvancedSearch(criteria, query);

2.修改查询变量逐步检查单个搜索条件

public static IQueryable<CustomMadeEntity> PerformAdvancedSearch(SearchRequestDto criteria, IQueryable< CustomMadeEntity > query) 
{
    if (!string.IsNullOrWhiteSpace(criteria.ArticleCode))
    {
        query = query.Where(el => el. ArticleCode == criteria. ArticleCode));
    }
}

包含、>

if (something) 
{
    query = query.Where(el => el.ArticleStatuses.OrderByDescending(el => el.CreatedOn).Any() &&
                              el.ArticleStatuses.OrderByDescending(el => el.CreatedOn)
                 .FirstOrDefault().LocationType == criteria.LocationType);                  
} 

【讨论】:

    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多