Reputation: 147
This is the code snippet.
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
+ "FROM Person "
+ "WHERE Discriminator = 'Student' "
+ "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);
System.IO.File.WriteAllText(@"C:\Users\Admin\Desktop\log.txt", data.ToString()); // or ToList()?
Now from my last line of code, I am getting a file with basically the same text that's there in the query. What I want to be displayed in my text file is the actual data from the database? How do I get that?
Upvotes: 0
Views: 144
Reputation: 68655
data.ToString()
returns the information about the class, not the data. You need to do like this
StringBuildet text = new StringBuilder();
data.ToList().ForEach(d => text.Append(/* Here what you want to do with each item of the EnrollmentDataGroup /*));
System.IO.File.WriteAllText(@"C:\Users\Admin\Desktop\log.txt", text);
First you need to cast to List for using the ForEach.
Or you can write your own ForEach
method for the type of IEnumerable
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
Upvotes: 2
Reputation: 2032
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
reference: https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx
Upvotes: 1