【问题标题】:How to get Random entries from database in mvc4 using Linq如何使用 Linq 从 mvc4 中的数据库中获取随机条目
【发布时间】:2014-11-29 20:29:41
【问题描述】:

我希望我的搜索从数据库中返回随机条目。如何执行此操作?
这是我的搜索功能,我正在使用加入查询并采用新模型来传递属性。

var planetfeedsOrder = from a in db.PlanetFeeds
                       where a.PlanetFeedOwnerId == id || a.PlanetFeedPosterId == id
                       && a.CurrentState != 1
                       join c in db.Graphs on a.PlanetFeedItemGraphId equals c.GraphID
                       join u in db.UserInfos on a.PlanetFeedOwnerId equals u.UserInfoID
                       orderby a.PostDate descending
                       select new UserInfoViewModel
                       {
                        AvatarURL = u.AvatarURL,
                        UserName=u.FirstName +" "+u.LastName,
                        GraphItemDescription = c.GraphItemDescription,
                        GraphItemURL = c.GraphItemURL,   
                        isRootFeed = a.isRootFeed,
                        PostDate = a.PostDate,
                        CurrentState = a.CurrentState,
                        };                    
return PartialView("_PlanetfeedPartial",planetfeedsOrder.Take(itemCount).ToList());

【问题讨论】:

标签: linq asp.net-mvc-4


【解决方案1】:

通过插入 guid(随机),orderby 的顺序将是随机的。:

  planetfeedsOrder.OrderBy(c => Guid.NewGuid()).Take(itemCount).ToList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2015-10-21
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多