简体   繁体   English

如何在ef core中获取具有条件顺序的实体

[英]How to get entities with order of condition in ef core

I have query with OR condition:我有 OR 条件的查询:

 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:主上下文 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>();
        }
    }

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();

LIVE DEMO现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM