0

I work with entity core and have a database table Id, Name, Organization, Phone

I give the user the opportunity to choose from it by any combination of fields for further export to excel He can choose For example: id and name or name, organization, phone.

How can I correctly compose a query with linq in the database to search for this data to export it?

sasha
  • 11
  • 2
  • 1
    Please show us your best non-satisfactory attempt. – Fildor Apr 03 '20 at 14:25
  • The easiest solution is to separate your data storage + retrieval (linq query) from your presentation (export to file). So the real question is not how to retrieve the data, but how to distinguish between the fields to be exported. Please add some details on what you do to export the data. – Björn Boxstart Apr 03 '20 at 14:26
  • 2
    Duplicate with https://stackoverflow.com/questions/16516971/linq-dynamic-select. Please find a solution there. – Björn Boxstart Apr 03 '20 at 14:31

1 Answers1

0

If I understand the question as this is an export function, and the user can pass in those extra fields to the final where clause we will use on the DB, then:

//at this point it is an IQueryable so we have not made an execute request to the DB
//atm it is equivalent to SELECT * FROM MyTable Where Id = idPassedIn
var myData = myDataContext.MyTable.Where(x => x.Id == idPassedIn);

if(!string.IsNullOrEmpty(namePassedIn)) {
   myData += myData.Where(x => x.Name == namePassedIn);
}

//continue with this type of if statements for all possible fields a user can send. 
//Now, we can send the execute command to the server. I am assuming it returns a 
//collection at this time.
return myData.ToList();

Let me know if I misunderstood your question

SomeStudent
  • 2,856
  • 1
  • 22
  • 36