Sam M
Sam M

Reputation: 1087

How to create a LINQ or Entity SQL query to get record from a Table where Table Name is achieved at runtime

My application is in Asp.net MVC3 coded in C#.Net. I have a view which has a DropDownList.This dropdownlist has the Name of all the Tables that are present in my database. My requirement is when the user selects a particular Table from the Dropdownlist then thru Json im passing the Name of the table to a Json method as is shown in the below Code.

$("#MyTableNames").change(function () {                                         
    $("#MyDiv").load("/../MyController/MyActionMethod", { TableName:$("#MyTableNames").val() }, function () {
    });
});

Above is how im passing my table name to my Action in the controller. Till here all is fine. Below is my Action Code. I have tried Two methods to write a query...It includes the Entity SQL aswell.No LINQ as LINQ doesnt support this.

 //First Method


  public ActionResult MyAction(string TableName)
            {

         var model = db.ExecuteStoreQuery<TableName>("Select * from " + TableName + "      where Delete_Flag='" + false + "'");
ViewBag.MyData=model;
                return PartialView();
            }

//Second Method


    public ActionResult GetRecords(string TableName)
            {
             var sql = "SELECT VALUE emp FROM " + TableName + " AS emp ";
             var query = db.CreateQuery <TableName>(sql);
             Viewbag.MyData=query;       
             return PartialView();
            }

But none of the above methods working as <>want the parameter as the table... I want to pass the result of the query to the VierwBag so that i can populate it in the View. Suggest how can i achieve this.

Upvotes: 1

Views: 410

Answers (1)

Chandermani
Chandermani

Reputation: 42669

Since you don't know the type to use during design time, it would be difficult to use strongly typed generics.

Another approach would be to using ExpandoObject\dynamic with micro ORM frameworks such as Massive to query data. The data returned in this case is a ExpandoObject, which if required can be returned back to client.

Upvotes: 1

Related Questions