如何在linqtosql中获得随机行
本文关键字:随机 linqtosql | 更新日期: 2023-09-27 18:05:23
我想通过使用linqtosql从数据库中随机获取一行,但我的要求是一些不同的....
我的代码是这样的
var qry = from tb in DC.tbcategory
where tb.parentID == null
order by tb.sortOrder
select new
{
categoryID = tb.CategoryID,
ImageID = (from tb in DC.tbImage
where tb.CategoryID == tc.CategoryID
orderby Guid.NewID()
select tb.ImageID).FirstorDefault()
}
在这个例子中tbcategory和tbimage有一对多的关系,我想取tbimage表的随机记录
试试这个
在SQL server中为随机记录创建视图
CREATE VIEW RandomView
AS
SELECT NEWID() As ID
在SQL server中创建一个函数
CREATE FUNCTION GetNewId
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN (SELECT ID FROM RandomView)
END
然后像这样使用linq查询
var qry = from tb in DC.tbcategory
where tb.parentID == null
order by tb.sortOrder
select new
{
categoryID = tb.CategoryID,
ImageID = (from tb in DC.tbImage
where tb.CategoryID == tc.CategoryID
orderby DC.GetNewId()
select tb.ImageID).FirstorDefault()
}
我希望它一定会起作用....
也许您可以在结果集上使用此扩展方法。这是URL