Reputation: 15
I have a table in my database. I want to save all SQL SERVER Database Table records into the array.I searched everywhere all I am getting is to copying data from dataTable to array. Is that possible save all records into the array from the database table? If yes please help me. I would like to get the code in C#.
Edited: I want to process all the rows in the DataTable but going row by row through Datatable is consuming more time. So I am looking for better performance with other features like arrays or structures may be.
Upvotes: 0
Views: 3902
Reputation: 7449
You could use EF and load your data like this:
var data = context.YourTable.ToList();
but be aware that if you have a big table it may slow down your application and then you have to do some workarounds like paging. usually you may want to pass some criteria in Where extension method
also you can run a raw SQL query with EF:
context.Database.SqlQuery<YourMappingClass>("SELECT * FROM YourTable")
choosing how to connect to your databse is a matter of preference, I prefer EF you can use ADO.NET.
Using ADO:
using(SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=[server_name];Database=[database_name];Trusted_Connection=true";
SqlCommand command = new SqlCommand("SELECT * FROM YourTable", conn);
}
using (SqlDataReader reader = command.ExecuteReader())
{
var list = new List<YourMappingClass>();
while (reader.Read())
{
var obj = new YourMappingClass();
obj.Prop1=reader[0];
obj.Prop2=reader[1];
list.Add(data);
}
}
Upvotes: 0
Reputation: 12745
Not sure what you are trying but seems pretty expensive and probably not a good idea , we can probably find another approach to deal with your problem and take this one out completely.
However for your question , the answer goes something like this:
public static void Main(string args[])
{
List<object> objectList = new List<object>();
var commandText = "Select name from sys.tables";
SqlConnection sqlConn = null;//Initialize
SqlCommand command = new SqlCommand(commandText, sqlConn);
var sqlReader = command.ExecuteReader();
while (sqlReader.Read())
{
commandText = $"Select * from {sqlReader["name"]}";
command = new SqlCommand(commandText, sqlConn);
var subReader = command.ExecuteReader();
while (subReader.Read())
{
//Loop through and add to list
objectList.Add();
}
}
}
Upvotes: 2