Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert List<T> into database

Tags:

c#

sql-server

How can I save a List in a database at once without iterating through the whole list and saving each object seperately to the database.

//So not like this solution
foreach(T t in data){
    //Call function to save with stored procedure
    Database.Save(t);
}

(Also without using the entity framework) (I only seem to get solutions based on the entity framework or Dapper.Net on StackOverflow.)

Is this even possible by sending the list in some way to the database and using a stored procedure?


@Edit Additional information

I'm currently running on SQL 2012 and want to be able to reroll everything if something did not work!

like image 223
Revils Avatar asked Feb 08 '23 00:02

Revils


2 Answers

If you are using at least SQL Server 2008, then you can use a Table Valued parameter to do this. This question and answers covers the topic.

Essentially you create a Type in SQL, and then something in C# to convert you data to a IEnumerable<SqlDataRecord> which matches the type as given.

like image 139
NikolaiDante Avatar answered Feb 16 '23 04:02

NikolaiDante


You can use Table Valued Parameter to pass collection to stored procedure. MSDN

like image 42
Ruslan K. Avatar answered Feb 16 '23 02:02

Ruslan K.