0

I want to select a row from a Database using LINQ to Entities in Entity Framework in C#.

My arguements to method are :

  • string Database Context
  • string TableName
  • string fieldName/column

I want to select the row from table "TableName" dynamically based on these three parameters where "fieldName" matches a certain value.

Madhur Maurya
  • 1,016
  • 4
  • 19
  • 42

1 Answers1

1

You don't need entity framework to do something like this, you can use helper methods provided into dbContext to execute your custom query:

  public List<T> ListElements(string tableName, string columnName) {
    var db = new DbContext();
    var query = string.Format("SELECT {0} FROM {1}", tableName, columnName);
    var data = db.Database.SqlQuery<T>(query);
    return data;
  }

You can use this method to list items into table with specific type. Suppose you want to display all ids of a table named "Users" you can write this code:

var userIds = ListElements<int>("Users", "Id");
Roberto Conte Rosito
  • 2,080
  • 12
  • 22
  • Thats the way I am doing it now. I just wanted to remove the hard coded string and do it dynamically – Madhur Maurya Mar 01 '16 at 11:40
  • OK, now is different, I suggest you to see this related post: http://stackoverflow.com/questions/3463479/querying-entity-with-linq-using-dyanmic-field-name, hope it can help – Roberto Conte Rosito Mar 01 '16 at 11:43