当Guid不工作时,如何在LINQ to SQL中获取随机记录

当Guid不工作时,如何在LINQ to SQL中获取随机记录,linq,class,linq-to-sql,Linq,Class,Linq To Sql,我想选择一条随机记录。我使用LINQtoSQL进行查询,但我对这些不太熟悉(我更了解普通的SQL查询) 这是我的代码: public void giveRand() { var query = (from Performance in db.Performances.OrderBy(c => Guid.NewGuid()).Take(1) join Stage in db.Stages on Performance.stage

我想选择一条随机记录。我使用LINQtoSQL进行查询,但我对这些不太熟悉(我更了解普通的SQL查询)

这是我的代码:

public void giveRand()
    {
        var query = (from Performance in db.Performances.OrderBy(c => Guid.NewGuid()).Take(1)
                    join Stage in db.Stages on Performance.stage_id equals Stage.stage_id
                    join Artist in db.Artists on Performance.artist_id equals Artist.artist_id

                    select new AllClass(db)
                    {
                        all_performance_id = Performance.performance_id,
                        all_starttime = Performance.starttime,
                        all_endtime = Performance.endtime,
                        all_artistname = Artist.name,
                        all_stagename = Stage.name,
                        all_artistdesc = Artist.description,
                        all_stagedesc = Stage.description
                    }).Single();
        App.Current.Properties["timestart"] = query.all_starttime;
        App.Current.Properties["timeened"] = query.all_endtime;
        App.Current.Properties["namea"] = query.all_artistname;
        App.Current.Properties["names"] = query.all_stagename;
        App.Current.Properties["desca"] = query.all_artistdesc;
        App.Current.Properties["descs"] = query.all_stagedesc;
}

我不知道出了什么问题。

我会按照评论中的建议,重写一点查询

但是,要回答您的问题,您可以使用Skip(random)+Take(1):


“当Guid不工作”是什么意思?你想选择什么记录并基于什么?那
AllClass(db)
也很可疑。DbContext就像连接一样是短暂的。您可能有一个长期存在的DbContext,或者当您试图通过已释放的DbContext访问数据时,您可能会遇到
ObjectDisposedException
s风险。您应该能够编写
db.performance.FirstOrDefault(someCriteria)
来检索第一个性能及其所有关系。或者写入
db.performance.Select(p=>newallclass{all\u artistname=p.Artist.name,…}).FirstOrDefault()
以获得单个匹配项。您真正使用的ORM是哪种?EF将为
Guid.NewGuid()
发出
NEWID()。你真的在使用10年前的LINQtoSQL吗?顺便说一句,整个查询都有问题。连接由ORM基于实体之间的关系生成。很少有理由在LINQ中使用联接。LINQ不是SQL的替代品,EF(或者L2S,如果你真的使用它的话)是ORM,不是通用的数据访问库。这会给我一个随机记录吗?
Random r = new Random();
int n = // number of records

var record = ... /* linq query */ .Skip(r.Next(0, n)).Take(1)