Offer Offer - 1 year ago 50
MySQL Question

Is it possible to return string values from a query when using Entity-Framework?

So far I know two ways to query the database. One of it is by using MySQL's Libraries; By declaring "MySqlCommand", "MySqlDataReader", "MySqlConnection" and utilizing the inbuilt methods.

And another is through using the Entity Framework (Which is my preferred option).

I've however run into a bit of a problem with this later method. I personally blame my lack of knowledge. It would seem that when conveying data to the end user, Entity-Framework favours the ObservableCollection<> or List<>.

For me, this means that in the View, I'd be using a Datagrid or List control. Normally this would be fine.

But then, what happens if I don't want a datagrid control in the mix? What if I want the query's result conveyed in a textboxes? How can I do the below without sacrificing the usage of the entity framework? Is it even possible?

string config = "server=localhost; userid = root; database = databaseName";
MySqlConnection con = new MySqlConnection(config);

MySqlDataReader reader = null;

// Run the select query
string query = "SELECT * FROM students WHERE id = " +id;

MySqlCommand command = new MySqlCommand(query, con);
reader = command.ExecuteReader();

while (reader.Read())
// Put the results in the appropriate strings so I can databind them
string studentName = (string)reader["studentName"];

string studentNum = (string)reader["studentNum"];


How could I do this utilising the entity framework?

Answer Source

EF equivalents for this SQL query:

// note, that this leads to SQL injections,
// use parametrized queries instead!
"SELECT * FROM students WHERE id = " +id

will be:

var student = context.Students.Find(id) // this will lookup local data as well


var student = context.Students.Single(_ => _.Id == id)

Both will return single Student instance, not a sequence/collection, and you can bind your UI to its properties or access them as usual: