user845802
user845802

Reputation:

How to get random row in linqtosql?

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.

Upvotes: 4

Views: 395

Answers (2)

Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

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....

Upvotes: 3

Abbas
Abbas

Reputation: 14432

Perhaps you can use this extension method on your resultset. Here's the URL.

Upvotes: 0

Related Questions