Translate an IQueryable instance to LINQ syntax in a string

Posted by James Dunne on Stack Overflow See other posts from Stack Overflow or by James Dunne
Published on 2010-06-10T13:56:58Z Indexed on 2010/06/11 20:53 UTC
Read the original article Hit count: 160

Filed under:
|

I would like to find out if anyone has existing work surrounding formatting an IQueryable instance back into a LINQ C# syntax inside a string. It'd be a nice-to-have feature for an internal LINQ-to-SQL auditing framework I'm building. Once my framework gets the IQueryable instance from a data repository method, I'd like to output something like:

This LINQ query:

from ce in db.EiClassEnrollment
join c in db.EiCourse on ce.CourseID equals c.CourseID
join cl in db.EiClass on ce.ClassID equals cl.ClassID
join t in db.EiTerm on ce.TermID equals t.TermID
join st in db.EiStaff on cl.Instructor equals st.StaffID
where (ce.StudentID == studentID) && (ce.TermID == termID) && (cl.Campus == campusID)
select new { ce, cl, t, c, st };

Generates the following LINQ-to-SQL query:

DECLARE @p0 int;
DECLARE @p1 int;
DECLARE @p2 int;
SET @p0 = 777;
SET @p1 = 778;
SET @p2 = 779;
SELECT [t0].[ClassEnrollmentID], ..., [t4].[Name]
FROM [dbo].[ei_ClassEnrollment] AS [t0]
INNER JOIN [dbo].[ei_Course] AS [t1] ON [t0].[CourseID] = [t1].[CourseID]
INNER JOIN [dbo].[ei_Class] AS [t2] ON [t0].[ClassID] = [t2].[ClassID]
INNER JOIN [dbo].[ei_Term] AS [t3] ON [t0].[TermID] = [t3].[TermID]
INNER JOIN [dbo].[ei_Staff] AS [t4] ON [t2].[Instructor] = [t4].[StaffID]
WHERE ([t0].[StudentID] = @p0) AND ([t0].[TermID] = @p1) AND ([t2].[Campus] = @p2)

I already have the SQL output working as you can see. I just need to find a way to get the IQueryable to translate into a string representing its original LINQ syntax (with an acceptable translation loss). I'm not afraid of writing it myself, but I'd like to see if anyone else has done this first.

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#3.0