防止 entity framework 中联合的排序结果

Prevent sort result of union in entity framework

在SQL 服务器union 中,结果根据主键列排序。我想在 entity framework.
中防止这种行为 在 this post 中,@praveen 解释了如何在 sql 中做到这一点。但我想在 entity framework.
中执行此操作 我的代码:

public virtual ActionResult Search(string keyword)
{
    var products = _db.Products
        .Where(x => x.IsActive)
        .AsQueryable();

    var productExactlyTitle = products.Where(x => x.Title == keyword);
    var productStartTitle = products.Where(x => x.Title.StartsWith(keyword));
    var productContainsTitle = products.Where(x => x.Title.Contains(keyword)
                                                   || x.Title.Contains(keyword)
                                                   || x.SubTitle.Contains(keyword)
                                                   || x.OtherName.Contains(keyword));


    var productList = productExactlyTitle.Union(productStartTitle)
        .Union(productContainsTitle)
        .Take(10)
        .AsEnumerable()
        .Select(x => new ProductItemViewModel()
        {
            Id = x.Id,
            Title = x.Title,
            Price = x.Price.ToPrice(),
            Image = x.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
        });

        // some code ...        
}

我想按以下顺序显示记录:

第一个:productExactlyTitle
的记录 第二:productStartTitle
的记录 第三:productContainsTitle

的记录

但结果按 Id 列排序!我不想要这个。

有办法吗?

在 SQL 中,所有未明确设置 order by 的查询都被视为无序。 (并且 EF 查询 a 翻译成 SQL)。所以如果你想在你的工会之后有一个特定的订单,只需指定它。

var result = q1.Union(q2).OrderBy(x => x.?);

针对您的具体情况:

var p1 = productExactlyTitle.Select(x => new { Item = x, Order = 1 });
var p2 = productStartTitle.Select(x => new { Item = x, Order = 2 });
var p3 = productContainsTitle.Select(x => new { Item = x, Order = 3 });
var productList = p1.Union(p2)
                    .Union(p3)
                    .OrderBy(x => x.Order)
                    .Select(x => x.Item)
                    .Take(10);