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

Firstly, I do not use dynamic , I just use such code, and it works well.

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

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

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

and I add such a method, I am building a project that shows that List does not have an 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(); } 
+5
source share
2 answers

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

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

  • Do not use dynamic . Instead, make Student and Teacher implement a common interface (e.g. IPerson ) and use this:

     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(); 
  • Call AsQueryable() as a regular static method:

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

By the way, checking that sex is older than 30 does not make any sense to me. You should probably rethink this part of your design.

+5
source

This is similar to this question.

As pointed out by @jbtule, anonymous types are internal; if you cross assembly boundaries, dynamic cannot resolve the property.

Instead of using an anonymous type, try using the actual type or Expando object.

-2
source

Source: https://habr.com/ru/post/1214785/


All Articles