相关疑难解决方法(0)

从Linq到Sql的随机行

当我有条件时,使用Linq to SQL检索随机行的最佳(和最快)方法是什么,例如某些字段必须为true?

.net c# linq-to-sql

110
推荐指数
5
解决办法
6万
查看次数

Linq to Entities,随机顺序

如何以随机顺序返回匹配的实体?
要明确这是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)

c# linq-to-entities entity-framework

36
推荐指数
3
解决办法
4万
查看次数

实体框架包括OrderBy随机生成重复数据

当我从包含一些孩子的数据库中检索项目列表(通过.Include),并随机排序时,EF给我一个意想不到的结果..我创建/克隆添加项目..

为了更好地解释自己,我创建了一个小而简单的EF CodeFirst项目来重现问题.首先,我将为您提供此项目的代码.

该项目

创建一个基本的MVC3项目,并通过Nuget添加EntityFramework.SqlServerCompact包.
这会添加以下软件包的最新版本:

  • EntityFramework v4.3.0
  • SqlServerCompact v4.0.8482.1
  • EntityFramework.SqlServerCompact v4.1.8482.2
  • WebActivator v1.5

模型和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)

linq random asp.net-mvc entity-framework sql-order-by

17
推荐指数
4
解决办法
6460
查看次数

如何从可用数字中获取随机数?

我有一张桌子,我试图从中获取一个随机数:

//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())

如何从可用数字中获取随机数?

c# entity-framework

3
推荐指数
1
解决办法
126
查看次数