i want to take a random row from database by using linqtosql, but my requirement is some different....
my code is this...
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()
}
in this example tbcategory and tbimage has one to many relation and i want to take random record of tbImage table.
Try this
Create a view in SQL server for take a random record
CREATE VIEW RandomView
AS
SELECT NEWID() As ID
Then create a functin in SQL server
CREATE FUNCTION GetNewId
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN (SELECT ID FROM RandomView)
END
then use you linq query like this
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()
}
I hope it will work definitely....
Perhaps you can use this extension method on your resultset. Here's the URL.
精彩评论