مرتب سازی رکوردها به صورت اتفاقی در Entity framework
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۷/۰۷ ۹:۵۸
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
SELECT * FROM table ORDER BY NEWID()
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
namespace Sample
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
}
public class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(MyContext context)
{
context.Users.Add(new User { Name = "User 1", Age = 20 });
context.Users.Add(new User { Name = "User 2", Age = 25 });
context.Users.Add(new User { Name = "User 3", Age = 30 });
context.Users.Add(new User { Name = "User 4", Age = 35 });
context.Users.Add(new User { Name = "User 5", Age = 40 });
base.Seed(context);
}
}
public static class Test
{
public static void RunTests()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
using (var context = new MyContext())
{
var randomListOfUsers =
context.Users
.Where(person => person.Age >= 25 && person.Age < 40)
.OrderBy(person => Guid.NewGuid())
.ToList();
foreach (var person in randomListOfUsers)
Console.WriteLine("{0}:{1}", person.Name, person.Age);
}
}
}
}
.OrderBy(person => Guid.NewGuid())
ORDER BY NEWID()
SELECT [Project1].[Id] AS [Id], [Project1].[Name] AS [Name], [Project1].[Age] AS [Age] FROM ( SELECT NEWID() AS [C1], ------ Guid created here [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[Age] AS [Age] FROM [dbo].[Users] AS [Extent1] WHERE ([Extent1].[Age] >= 25) AND ([Extent1].[Age] < 40) ) AS [Project1] ORDER BY [Project1].[C1] ASC ------ Used for sorting here
SELECT * FROM Table1 WHERE (ABS(CAST( (BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 10
var query = (from list in dbContext.Packages
where list.Id == Int32.Parse(Request["Id"].ToString())
select list).FirstOrDefault();
Int32 ID = Int32.Parse(Request["Id"].ToString());
var query = (from list in dbContext.Packages
where list.Id == ID
select list).FirstOrDefault();