Reputation: 3032
I have query with OR condition:
MainContext mainContext = new MainContext();
var entities = mainContext.GetEntities<Student>().Where(s =>
s.Guid == new Guid("4A6C8A8D-92E5-48A4-1C53-08D8A65747F0") ||
s.Guid == new Guid("D3D41AA0-8E68-43FA-1C51-08D8A65747F0") ||
s.Guid == new Guid("6304347D-A169-4251-1C52-08D8A65747F0")).ToList();
I want to get entity instances with "correct" order. I am expecting:
var first = entities[0]; // 4A6C8A8D-92E5-48A4-1C53-08D8A65747F0
var second = entities[1];//D3D41AA0-8E68-43FA-1C51-08D8A65747F0
var third = entities[2];//6304347D-A169-4251-1C52-08D8A65747F0
But actual result is:
var first = entities[0]; // D3D41AA0-8E68-43FA-1C51-08D8A65747F0
var second = entities[1];//6304347D-A169-4251-1C52-08D8A65747F0
var third = entities[2];//4A6C8A8D-92E5-48A4-1C53-08D8A65747F0
How can I order or ordered query to db?
MainContext class:
public class MainContext : DbContext
{
public MainContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer($"Server=localhost;Database=EFCoreLessonDecimalCHeck;Trusted_Connection=True;MultipleActiveResultSets=true");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasKey(d => d.Guid);
modelBuilder.Entity<Person>().Property(s => s.DecimalProperty).HasDefaultValue(0).HasColumnType("decimal(28,10)");
modelBuilder.Entity<Student>();
modelBuilder.Entity<Teacher>();
base.OnModelCreating(modelBuilder);
}
public IQueryable<T> GetEntities<T>() where T : class
{
return Set<T>();
}
}
Upvotes: 2
Views: 383
Reputation: 34150
Just use the order by:
var entities = mainContext.GetEntities<Student>().Where(s =>
s.Guid == new Guid("4A6C8A8D-92E5-48A4-1C53-08D8A65747F0") ||
s.Guid == new Guid("D3D41AA0-8E68-43FA-1C51-08D8A65747F0") ||
s.Guid == new Guid("6304347D-A169-4251-1C52-08D8A65747F0"))
.ToList()
.OrderByDescending(x => x.Guid == "4A6C8A8D-92E5-48A4-1C53-08D8A65747F0")
.ThenByDescending(x => x.Guid == "D3D41AA0-8E68-43FA-1C51-08D8A65747F0")
.ThenByDescending(x => x.Guid == "6304347D-A169-4251-1C52-08D8A65747F0")
.ToList();
Upvotes: 2