-1

I'm using Entity Framework with C#. And I want to getting columns with string column name like below. How can I achieve this?

I want like below

context.Students.Select({
"Name",
"Surname",
"Number",
"BirthDate",
}).ToList();

Please don't advice below solution

context.Students.Select(p=> new {
p.Name,
p.Surname,
p.Number,
p.BirthDate,
}).ToList();
realist
  • 2,155
  • 12
  • 38
  • 77
  • Why do you want to do it with strings literals? When something goes wrong it's harder to find what, and when you change something they won't throw compiler errors like the second solution will. – MindSwipe Nov 30 '18 at 08:08
  • (Sorry. I gave wrong link. This link is true.) My main aim is in this question https://stackoverflow.com/questions/53553305/exclude-columns-getting-data-with-entity-framework , but I quess that it is not possible.So I think this solution. I will get all property of model and erase some colums from list. @MindSwipe – realist Nov 30 '18 at 08:31
  • Everything is possible with enough time and knowledge, I'm just saying it doesn't make sense/ is dangerous to use string literals instead of `p => new { p.Name ...}` – MindSwipe Nov 30 '18 at 09:01
  • I found the solution by creatiing class with these properties. And then I used `ProjectTo` method of `AutoMapper`. https://stackoverflow.com/questions/53558512/getting-only-some-columns-in-dto-class-from-table-by-entity-framework and http://docs.automapper.org/en/stable/Queryable-Extensions.html – realist Nov 30 '18 at 21:06

1 Answers1

0

I don't think this is supported out of the box.

You can use context.Students.SqlQuery but then you will need to pass a complete SQL Statement.

Alternatively you may need to create some helper that maps string to properties, but that will involve reflection.

Nick
  • 4,787
  • 2
  • 18
  • 24
  • SqlQuery maybe a solution. But, my main aim is in this question https://stackoverflow.com/questions/53553305/exclude-columns-getting-data-with-entity-framework. So, I will take columns names automatically and will create query. But, I hope, I can find better way from SqlQuey. Because, it's very difficult create dinamically `where` filter with sql query @Nick – realist Nov 30 '18 at 08:40