当我有条件时,使用Linq to SQL检索随机行的最佳(和最快)方法是什么,例如某些字段必须为true?
如何以随机顺序返回匹配的实体?
要明确这是Entity Framework的东西和LINQ to Entities.
(航空代码)
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby ?????
select en;
Run Code Online (Sandbox Code Playgroud)
谢谢
编辑:
我尝试将其添加到上下文中:
public Guid Random()
{
return new Guid();
}
Run Code Online (Sandbox Code Playgroud)
并使用此查询:
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby context.Random()
select en;
Run Code Online (Sandbox Code Playgroud)
但我得到了这个错误:
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Guid Random()' method, and this method cannot be translated into a store expression..
Run Code Online (Sandbox Code Playgroud)
编辑(当前代码):
IEnumerable<MyEntity> results = (from en in context.MyEntity
where …Run Code Online (Sandbox Code Playgroud) 当我从包含一些孩子的数据库中检索项目列表(通过.Include),并随机排序时,EF给我一个意想不到的结果..我创建/克隆添加项目..
为了更好地解释自己,我创建了一个小而简单的EF CodeFirst项目来重现问题.首先,我将为您提供此项目的代码.
创建一个基本的MVC3项目,并通过Nuget添加EntityFramework.SqlServerCompact包.
这会添加以下软件包的最新版本:
模型和DbContext
using System.Collections.Generic;
using System.Data.Entity;
namespace RandomWithInclude.Models
{
public class PeopleContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Address> Addresses { get; set; }
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int ID { get; set; …Run Code Online (Sandbox Code Playgroud) 我有一张桌子,我试图从中获取一个随机数:
//Fruits
id | FruitName
----------------
2 | Banana
3 | Apple
4 | Orange
6 | Grape
7 | Plum
8 | Lime
10 | Kiwi
Run Code Online (Sandbox Code Playgroud)
问题是由于不一致(注意:缺少ID 1,5和9),编写以下语句将不起作用(即使写得正确):
Random.Next(someLinq.id).First(), (samelinq.id).Last())
如何从可用数字中获取随机数?