Without specifics, here is how to get random records from a model.
public static List<Products> RandomProducts(int count)
{
using var context = new Context();
Random rand = new Random();
int skipper = rand.Next(0, context.Products.Count());
return context
.Products
.OrderBy(product => Guid.NewGuid())
.Skip(skipper)
.Take(count)
.ToList();
}
Usage
var products = CoreOperations.RandomProducts(7);
foreach (var product in products)
{
Console.WriteLine($"{product.ProductId,-4}{product.ProductName}");
}
Edit, here is a generic method
/// <summary>
/// Get list of random records for <see cref="TModel"/> by <see cref="count"/>
/// </summary>
/// <typeparam name="TModel">Model to read</typeparam>
/// <param name="count">Max records</param>
/// <returns>List of <see cref="TModel"/></returns>
/// <remarks>
/// Not guaranteed to return <see cref="count"/> but will return records
/// </remarks>
public static List<TModel> Random<TModel>(int count) where TModel : class
{
using var context = new Context();
Random rand = new Random();
int skipper = rand.Next(0, context.Set<TModel>().Count());
return context.Set<TModel>().ToList()
.OrderBy(x => Guid.NewGuid())
.Skip(skipper)
.Take(count).ToList();
}
Usage
List<Products> products = CoreOperations.Random<Products>(7);
foreach (var product in products)
{
Console.WriteLine($"{product.ProductId,-4}{product.ProductName}");
}
Console.WriteLine();
List<Categories> categories = CoreOperations.Random<Categories>(3);
foreach (var product in categories)
{
Console.WriteLine($"{product.CategoryId,-4}{product.CategoryName}");
}