Lets say I have an IEnumerable
IEnumerable<Students> = from a in context.Students select a
Is there any way to execute
from a in context.Students select a
from a string?
Asked
Active
Viewed 65 times
0

Shawn Invento
- 13
- 5
-
*from a string?...* don't think so – Rahul May 10 '17 at 10:51
-
http://stackoverflow.com/questions/11479525/how-to-turn-a-string-into-a-linq-expression – ColinM May 10 '17 at 11:00
2 Answers
0
You can do it like this:
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
IEnumerable<Customer> results = db.ExecuteQuery<Customer>
(@"SELECT c1.custid as CustomerID, c2.custName as ContactName
FROM customer1 as c1, customer2 as c2
WHERE c1.custid = c2.custid"
);
However it also loses some of the key benefits of using an ORM in the first place. Automatic data binding and automatic parameter binding (thus preventing SQLi attacks)

ste-fu
- 6,879
- 3
- 27
- 46
-
-
-
@AkosNagy Good point....I read the question slightly differently and now I am not sure if the answer is relevant. Maybe OP will comment? – ste-fu May 10 '17 at 10:59
-
1@ColinM Northwnd refers to the standard MS Northwind Database used for many demos of MS SQL. It is the equivent of `context` in the OP – ste-fu May 10 '17 at 11:01
-
@ste-fu something along the lines of `IEnumerable
studentlist = someFunction("from a in context.Students select a")`. someFunction returns an IEnumerable based on whichever query is passed in? – Shawn Invento May 10 '17 at 11:05 -
Perhaps more accurately, lets take an HQL example `String hql = "FROM com.hibernatebook.criteria.Employee"; Query query = session.createQuery(hql); List results = query.list();` – Shawn Invento May 10 '17 at 11:11
-
By the time is is a string you have lost all the type safety and compile time checking tho, so the two are equivalent no? – ste-fu May 10 '17 at 12:10
0
'Is there any way...?'
Sure there is. This is basically a piece of C# code that you want to run. So all you need is a way to compile this piece of code into a valid assembly, load the assembly and run this piece of code. The .NET Compiler Platform ("Roslyn") or maybe even CodeDom can help you with that. But bear in mind that this can be quite complicated.

Akos Nagy
- 4,201
- 1
- 20
- 37