How to get random string in linqtosql?

I want to take a random row from a database using linqtosql, but my requirement is slightly different.

my code is ...

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 are one to many, and I want to take a random tbImage table entry.

+4
source share
2 answers

try it

Create a view in SQL server to record a random record

 CREATE VIEW RandomView AS SELECT NEWID() As ID 

Then create functin on SQL server

 CREATE FUNCTION GetNewId ( ) RETURNS uniqueidentifier AS BEGIN RETURN (SELECT ID FROM RandomView) END 

then use 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 this works definitely ....

+3
source

Perhaps you can use this extension method in your result set. Here is the url .

0
source

All Articles