Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between my codes when I use 'dynamic' to use AsQueryable method?

At first,I do not use dynamic,I just use the code like this,and it works well.

  List<Student> result2 = StudentRepository.GetStudent(sex,age).ToList();
  IQueryable rows2 = result2.AsQueryable();

But when I change it to dynamic,it is wrong.

 dynamic result = GetPeopleData(sex,age);
 IQueryable rows = result.AsQueryable();

and I add a method like this,I build the project it show that List do not have the AsQueryable method.How to change it?

 private dynamic GetPeopleData(int sex, int age)
    {
        if(sex>30)
            return StudentRepository.GetStudent(sex,age).ToList();
        else
            return TeacherRepository.GetTeacher(sex, age).ToList();
    }
like image 591
flower Avatar asked Oct 20 '22 16:10

flower


1 Answers

AsQueryable() is an extension method and those don't work on dynamic.

Depending on what you want to do, there are several possible solutions:

  1. Don't use dynamic. Instead, make Student and Teacher implement a common interface (say, IPerson) and use that:

    private IReadOnlyList<IPerson> GetPeopleData(int sex, int age)
    {
        if (sex > 30)
            return StudentRepository.GetStudent(sex, age).ToList();
        else
            return TeacherRepository.GetTeacher(sex, age).ToList();
    }
    
    …
    
    var result = GetPeopleData(sex, age);
    IQueryable<IPerson> rows = result2.AsQueryable();
    
  2. Call AsQueryable() as a normal static method:

    dynamic result = GetPeopleData(sex, age);
    IQueryable rows = Queryable.AsQueryable(result);
    

BTW, checking whether sex is over 30 doesn't make any kind of sense to me. You should probably rethink that part of your design.

like image 82
svick Avatar answered Oct 22 '22 08:10

svick