c# - 使用 IQueryable 返回随机行

标签 c# asp.net linq

我有一个将 ListView 绑定(bind)到 IQueryable 的 ASP.NET 页面:

<asp:ListView ID="productList" runat="server" 
    DataKeyNames="ProductID" GroupItemCount="6"
    ItemType="products.Models.Product" SelectMethod="GetProducts">
    <EmptyDataTemplate>
        <div>
            Sorry, no products available
        </div>
    </EmptyDataTemplate>
    <GroupTemplate>
        <ul id="da-thumbs" class="da-thumbs">
        <div id="itemPlaceholderContainer" runat="server" class="text-center">
            <div id="itemPlaceholder" runat="server"></div>
        </div>
        </ul>
    </GroupTemplate>
    <ItemTemplate>
        <li> 
            <img src='/products/Catalog/Images/Thumbs/<%#:Item.ImagePath%>' class="img-responsive"/>
            <div>
                <span class="hidden-xs">Short Description</span>
                <span class="spacer visible-xs"></span>
                <a href="<%#: GetRouteUrl("ProductByNameRoute", new {productName = Item.ProductName}) %>" class="btn btn-success btn-block align-mid">View Details</a>     
                <a href="<%#:Item.ShortURL %>" class="btn btn-success btn-block align-mid"><%#:Item.DownloadText%></a>
            </div>
        </li>
    </ItemTemplate>
    <LayoutTemplate>
        <div class="row">
            <asp:PlaceHolder ID="groupPlaceholderContainer" runat="server">
                <div id="groupPlaceholder" runat="server"></div>
            </asp:PlaceHolder>
        </div>                 
    </LayoutTemplate>
</asp:ListView>
<asp:DataPager ID="it" runat="server" PagedControlID="productList" PageSize="6" class="btn-group pager-buttons pagination pagination-large">
    <Fields>
        <asp:NextPreviousPagerField ShowLastPageButton="False" ShowNextPageButton="False" ButtonType="Button" ButtonCssClass="btn" RenderNonBreakingSpacesBetweenControls="false" />
        <asp:NumericPagerField ButtonType="Button" RenderNonBreakingSpacesBetweenControls="false" NumericButtonCssClass="btn" CurrentPageLabelCssClass="btn disabled" NextPreviousButtonCssClass="btn" />
        <asp:NextPreviousPagerField ShowFirstPageButton="False" ShowPreviousPageButton="False" ButtonType="Button" ButtonCssClass="btn" RenderNonBreakingSpacesBetweenControls="false" />
    </Fields>
</asp:DataPager>

GetProducts() 定义如下:

public IQueryable<Product> GetProducts(
                        [QueryString("id")] int? categoryId,
                        [RouteData] string categoryName)
{
    var _db = new products.Models.ProductContext();
    IQueryable<Product> query = _db.Products;

    if (categoryId.HasValue && categoryId > 0)
    {
        query = query.Where(p => p.CategoryID == categoryId);
    }

    if (!String.IsNullOrEmpty(categoryName))
    {
        query = query.Where(p =>
                            String.Compare(p.Category.CategoryName,
                            categoryName) == 0);
    }

    var random = new Random();
    query = query.OrderBy(product => random.Next()).Where (p => p.Active == 1);
    return query;
}

问题是 Random() 在这里不起作用。当我运行我的应用程序时,出现错误

LINQ to Entities does not recognize the method 'Int32 Next()' method, and this method cannot be translated into a store expression.

可能一种解决方案是将其更改为 IEnumerable 但随后我需要 IQueryable 进行分页。

更新:使用 Taher 的解决方案后,这是我得到的内部查询:

{SELECT 
    [Project1].[ProductID] AS [ProductID], 
    [Project1].[ProductName] AS [ProductName], 
    [Project1].[Description] AS [Description], 
    [Project1].[ImagePath] AS [ImagePath], 
    [Project1].[DownloadText] AS [DownloadText], 
    [Project1].[DownloadURL] AS [DownloadURL], 
    [Project1].[ShortURL] AS [ShortURL], 
    [Project1].[UnitPrice] AS [UnitPrice], 
    [Project1].[CategoryID] AS [CategoryID], 
    [Project1].[Active] AS [Active], 
    [Project1].[ShortDescription] AS [ShortDescription], 
    [Project1].[Priority] AS [Priority]
    FROM ( SELECT 
        RAND() AS [C1], 
        [Extent1].[ProductID] AS [ProductID], 
        [Extent1].[ProductName] AS [ProductName], 
        [Extent1].[Description] AS [Description], 
        [Extent1].[ImagePath] AS [ImagePath], 
        [Extent1].[DownloadText] AS [DownloadText], 
        [Extent1].[DownloadURL] AS [DownloadURL], 
        [Extent1].[ShortURL] AS [ShortURL], 
        [Extent1].[UnitPrice] AS [UnitPrice], 
        [Extent1].[CategoryID] AS [CategoryID], 
        [Extent1].[Active] AS [Active], 
        [Extent1].[ShortDescription] AS [ShortDescription], 
        [Extent1].[Priority] AS [Priority]
        FROM [dbo].[Products] AS [Extent1]
        WHERE 1 = [Extent1].[Active]
    )  AS [Project1]
    ORDER BY [Project1].[C1] ASC}

更新:这是使用 Taher 和 JCL 的建议修改后的代码:

if (!String.IsNullOrEmpty(categoryName))
{
    Session["rand"] = null;
    query = query.Where(p =>
                        String.Compare(p.Category.CategoryName,
                        categoryName) == 0);
}

var seed = 0;

if (Session["rand"] == null)
{
    seed = (int)DateTime.Now.Ticks % 9395713;//a random number
    Session["rand"] = seed;
}

var readSeed = (int)Session["rand"];
query = query
   .OrderBy(product => SqlFunctions.Rand(product.ProductID * readSeed % 577317));
return query;

最佳答案

有一类 EF 支持的函数称为 SqlFunctions .您可以使用此类的 Rand 函数:

 query = query.OrderBy(product => SqlFunctions.Rand()).Where (p => p.Active == 1);

不要忘记添加

 using System.Data.Entity.Core.Objects; 

这种方法的问题是 from this source :

Repetitive invocations of RAND() in a single query will produce the same value.

我认为没有任何解决方法。解决方案是在我认为对你没有用的原始 SQL 命令中使用 `Newid(),或者加载查询数据然后在内存中打乱行。

我试过这个解决方法,它似乎有效:

var seed = (int)DateTime.Now.Ticks % 9395713;//a random number
query = query
   .OrderBy(product =>SqlFunctions.Rand(product.ProductId * seed % 577317))
   .Where (p => p.Active == 1);

这个技巧将强制 sql server 为每一行生成一个新的随机值,因为 ProductId 在每一行上发生变化,这会改变 Rand 种子,从而强制 sql服务器生成新的随机值。

您可以探索 seed 变量的不同值以获得更好的结果。

编辑
为了每个类别都有一个种子,您可以在 Application 中创建一个种子缓存,或者简单地创建一个(类别,种子)对的静态字典,如下所示:

如果您使用 MVC,则在 Controller 中;如果您使用 ASP.NET,则在页面类中:

static Dictionary<string, int> categorySeeds = new Dictionary<string, int>();

在 Action 或方法中:

int seed = 0;
if(categorySeeds.ContainsKey(categoryName))
{
   seed = categorySeeds[categoryName];
}
else
{
   seed = (int)DateTime.Now.Ticks % 9395713;//a random number
   categorySeeds.Add(categoryName, seed);
}
//rest of the code

关于c# - 使用 IQueryable 返回随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391115/

相关文章:

c# - 在 asp 按钮单击事件中访问 Html TextBox 控件?

c# - 如何使用 padleft 表示负整数?

c# - 使我们的源代码副本类似于生产服务器上的代码编译副本

asp.net - .aspx 文件中的条件编译

c# - 网络客户端编码

c# - MVC 脚手架不支持 Entity Framework 6 或更高版本

asp.net - 根据查询字符串显示完全不同的输出

c# - LINQ 返回最大重复项但反向排序

c# - 将值传递给 Linq 中的 OrderBy 或 OrderByDescending 语句?

c# - 将 SQL 的结果除以单独的 List <int>