[asp.net]返回使用 IQueryable 的随机行

标签: Asp.net Linq C#
发布时间: 2017/3/26 2:52:12
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个 ASP.NET 页,将绑定到 listview IQueryable :

<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 到实体不承认 ' Int32 next () 方法,方法,此方法不能转化为一个存储表达式。

大概一个解决办法是将其更改为 IEnumerable ,但然后我需要 IQueryable 的分页。

更新︰ 使用后塔希尔的解决方案,这是我得到的内部查询︰

{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}

更新︰ 这里是修改后的代码使用塔希尔的和 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;

解决方法 1:

还有一类支持的函数,因为 EF 称为 SqlFunctions 。您可以使用 Rand 这类的函数︰

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

别忘了添加

 using System.Data.Entity.Core.Objects; 

这种方法的问题是这种来源

在单个查询中的重复调用 rand () 将产生相同的值。

我不认为还有任何周围为它的工作。解决方案是使用 ' Newid() 在原始的 SQL 命令,我认为是没有用处的你,或加载查询数据,然后再洗牌行在内存中。

我试过这项工作周围和它似乎工作︰

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 服务器生成一个新的随机值,对于每一行,作为 ProductId 上这会更改每个行的更改 Rand 强制 sql 服务器来生成新的随机值的种子。

您可以浏览不同的值 seed 变量,以获得更好的结果。

编辑
要有一颗种子,每个类别,您可以创建一个缓存的种子在 Application 或简单地创建 (类别,种子) 静态字典对,就像这样︰

如果您使用的控制器 MVC 或页类如果你使用 ASP.NET :

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

在操作或方法︰

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
赞助商