Evgeniy Labunskiy
Evgeniy Labunskiy

Reputation: 2042

Entity Random Select from DB C# MVC

Try to find the solution but i cant.

So problem is next one. I have the EDM model of database. I have a class with functions to get data from DB. Like this:

public IQueryable<photos> FindUserPhotos(string userlogin)
        {
            return from m in db.photos
                   where m.userlogin == userlogin
                   select m;
        }

How to get the Random 10 lines from DB?

Upvotes: 0

Views: 5022

Answers (2)

I always use this method for get custom entity OrderBy(x => Guid.NewGuid())

public photos Find10RandomUserPhotos(string userlogin)
{
   return db.photos.Where(x => x.userlogin == userlogin).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
}    

Upvotes: 4

ariel
ariel

Reputation: 16140

Following Random row from Linq to Sql

public photos FindRandomUserPhoto(string userlogin)
{
   var qry = FindUserPhotos(userlogin);
   int count = qry.Count();
   int index = new Random().Next(count);
   return qry.Skip(index).FirstOrDefault();
}

public Array<photos> Find10RandomUserPhotos(string userlogin)
{
   var result = New Array<photos>;
   for (i = 0; i < 10; i++) {
      result.add(FindRandomUserPhoto(userlogin));
   }
   return result
}

Upvotes: 0

Related Questions