euo , 13 Nov 2009

This is how to construct dynamic query in LINQ.

 Dynamic LINQ

Since I find it hard for me to create Join inside LINQTOSQL, I created a Stored Procedure for my select statement. I will just call the Store Procedure using LINQ and presto I have my resultsets.

That is all fine if I have a straight select statement. The problem happens when I have a dynamic statement and I need to create string command and then execute it using EXEC command inside the Stored Procedure. When a statement is build in this manner, the LINQTOSQL treated the result as int and not the INUMERABLE result. 

 

I cannot find a solution for now. I'll post it here once I was able to solve it. 

 

As I am experimenting with the new feature of VS 2008 - the LINQ, I came across of needing to bind a datasource to an object. The datasource that I want to use is the result of my LINQ query statement. Here is what I got and done.

First, create a LINQ-to-SQL class. 

 

 

Now that I already have my LINQ-to-SQL mark-up language, I can now run a query against it like to any ordinary database. Construct the query statement: 

            var db = new WITWAY_DATADataContext();
            var branches = from branch in db.Branches.AsEnumerable<Branch>()
                           select branch;

 The WITWAY_DATADataContext class is the generated object that the LINQ-to-SQL provided. It is where the representation of our database resides. The generic AsEnumerable<Branch> extension method tells that the we want the query's result to be enumerable of Batch type. 

 Now, bind the result to, say, DropdownList.

if (!IsPostBack)
        {         
            var db = new WITWAY_DATADataContext();
            var branches = from branch in db.Branches.AsEnumerable<Branch>()
                           select branch;

            ddlBranch.DataSource = branches;
            ddlBranch.DataValueField = "uid";
            ddlBranch.DataTextField = "Name";
            ddlBranch.DataBind();
        }