如何显示我从数据库中获得的数据.C#中的SqlQuery
本文关键字:数据 SqlQuery 中的 数据库 何显示 显示 | 更新日期: 2023-09-27 17:59:04
这是代码片段。
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()?
现在,从我的最后一行代码中,我得到了一个文件,该文件的文本与查询中的文本基本相同。我想在文本文件中显示的是数据库中的实际数据?我该怎么做?
data.ToString()
返回有关类的信息,而不是数据。你需要像这个一样
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);
首先,您需要强制转换到List以使用ForEach。或者,您可以为IEnumerable类型编写自己的ForEach
方法
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
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();
参考:https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx