I am moving a project from working with standard DB queries to working with EF and LINQ. I have a table that has certain records that I would use to build a query that would look like the following:
select * from client where city = ?
In my original table, I would be pulling client and city from the table to build that query.
It is also possible that client and city above could be another table and/or field altogether. How would I do the same thing with EF and LINQ? Is this even possible or do I have to build a separate class to handle all of that logic?
var query = from c in context.clients
where c.city == ?
select c;
Edit: This isn’t about joining queries. It’s about building dynamic queries. I don’t know when I run the program whether I will be querying on city, address, or any even on the “client” table itself. It could be on another table. I want to be able to dynamically build the queries.
If you want to build dynamic queries in Entity Framework, you CAN go through the trouble of trying to build the expression tree dynamically. However, the Entity Framework gives you some additional options.
First, EntityObject has some additional Object Services methods which already let you build a string and pass that in directly into a number of the predicates, including Where:
If you need to build larger queries, including dynamically setting the query source, consider using EntitySQL. For example with EntitySQL, you can use simple string parsing and generate code like the following:
You can see both of these options in action in the Entity Framework Query Samples.