0

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?

0

2 Answers 2

2

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

1 Comment

For the love of anything that's holy to you (the FSM for me) use a StringBuilder instead of repeated string concatenation !
1
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

Comments

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.