首页 > 数据库技术 > 详细

转:使用linq to sql 随机取一行数据的方法

时间:2015-05-21 17:07:46      阅读:308      评论:0      收藏:0      [点我收藏+]

原文地址:http://outofmemory.cn/code-snippet/1760/usage-linq-to-sql-suiji-take-yixing-data-method 虽然这看来已经不是真正的原文地址了

在linq to sql中我们可以通过创建一个假的用户自定义函数的方法来实现随机取一行数据的方法。

首先要在DataContext的类中添加用户自定义函数,最好是放在partial class中:

partial class MyDataContext {
     [Function(Name="NEWID", IsComposable=true)] 
     public Guid Random() 
     { // to prove not used by our C# code... 
         throw new NotImplementedException(); 
     }
}

现在我们可以使用 order by ctx.Random() 这样的效果是在sql-server中执行order by NEWID()

例如:

var cust = (from row in ctx.Customers
           where row.IsActive // your filter
           orderby ctx.Random()
           select row).FirstOrDefault();

注意: 这个方法如果用在数据量很大的表中有可能会有性能问题。

转:使用linq to sql 随机取一行数据的方法

原文:http://www.cnblogs.com/techfans/p/4520086.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!