搜索
 
您现在的位置: 跳过导航链接

在LINQ中使用NewID()随机排序

发布时间:2008.08.26 | 发布人:

first, create the following view:

create view randomview
as
select newid() as id

then create the following function that uses the view:

create function getnewid
(
)
returns uniqueidentifier
as
begin
return (select id from randomview)
end

the view is required because it's not possible to directly use newid in a scalar function.

you can then map the getnewid user-defined function using linq to sql's function attribute. again, see chapter 8 for the details.

that's it! you can now write linq queries as usual. here is an example to pick a random object:

var tool = db.tools.orderby(t => db.getnewid()).first()

here is another example that uses getnewid to sort results randomly: 

var tools =
  from tool in db.tools
  orderby db.getnewid()
  select tool.name;

【字体:】【打印此文】【关闭窗口
2006-2008© 秦天信息版权所有  闽ICP备08006290号 我要啦免费统计