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.

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

2 Comments

Thats the way I am doing it now. I just wanted to remove the hard coded string and do it dynamically
OK, now is different, I suggest you to see this related post: stackoverflow.com/questions/3463479/…, hope it can help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.