Linq to Sql 随机查询

linq to object中可以直接用

            var query = from p in Products
                        orderby Guid.NewGuid()
                        select p;

来获得随机排序的内容

linq to sql中,要在datacontext中加入newid的映射才可以随机排序

在context类中,加入一个新方法即可

        [Function(Name = "NEWID", IsComposable = true)]
        public Guid NEWID()
        {

            return ((Guid)(this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod()))).ReturnValue));

        }  

调用方法

            DataClasses1DataContext db = new DataClasses1DataContext();
            var query = from p in db.Product
                        orderby db.NEWID()
                        select p;
            
            Console.WriteLine(query.First().ID);

 

posted @ 2012-08-11 02:04  Bug山Bug海  阅读(1386)  评论(0编辑  收藏  举报