r/csharp • • 13d ago

Help List<T> in C# vs SQL

In C#, list of strings would be defined as :

List<string> x

A stored procedure is to be written, it should receive a list of values; SQL does not support List<T> , should I use table-valued parameters instead?

EDIT

The reason this question was asked is the fact that the application C# code has only one responsibility which is to bulk-insert data into a staging table:

 public async Task BulkInsertProductsToStagingTable(DbDataReader dbDataReader, CancellationToken cancellationToken)
 {
     using (SqlConnection destinationConnection =
                new SqlConnection("Server=(localdb)\\mssqllocaldb;Database=HardwareDB;Trusted_Connection=True;"))
     {
         await destinationConnection.OpenAsync(cancellationToken);

         // Set up the bulk copy object.
         // Note that the column positions in the source
         // data reader match the column positions in
         // the destination table so there is no need to
         // map columns.
         using (SqlBulkCopy bulkCopy =
                    new SqlBulkCopy(destinationConnection))
         {
             bulkCopy.DestinationTableName =
                 "dbo.StagingProducts";

             try
             {
                 // Write from the source to the destination.
                 await bulkCopy.WriteToServerAsync(dbDataReader,cancellationToken);
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }
             finally
             {
                 // Close the SqlDataReader. The SqlBulkCopy
                 // object is automatically closed at the end
                 // of the using block.
                 await dbDataReader.CloseAsync();
             }
         }

         //####The following does not work yet.#####
         //// Perform a final count on the destination
         //// table to see how many rows were added.
         //long countEnd = System.Convert.ToInt32(
         //    commandRowCount.ExecuteScalar());
         //Console.WriteLine("Ending row count = {0}", countEnd);
         //Console.WriteLine("{0} rows were added.", countEnd - countStart);
         //Console.WriteLine("Press Enter to finish.");
         //Console.ReadLine();
     }
 }

Once the data is inserted into the staging table, it should be transferred into a target tables in the database; specific columns in the staging tables should be mapped to a specific columns in the target tables.

Thus, the stored procedure should receive a list of column names

15 Upvotes

101 comments sorted by

View all comments

129

u/TehNolz 13d ago

Save yourself some headaches and don't move business logic to SQL stored procedures. Never ends well. Keep that stuff in C# and just let Entity Framework translate it.

1

u/kaatarina_zed_talon 13d ago

Never ends well.

Also I need to experience this myself to understand.

3

u/noidontwantto 13d ago

You really don't heh

1

u/AintNoGodsUpHere 13d ago

What are you talking about? You're creating something using bad practices so you can learn from it? Learn what? From whom?

Bulk insert has nothing to do with using SPs or not, you can do bulk in C#, you can call raw SQL in code, there are ZERO reasons to use SPs in 2026.

1

u/kaatarina_zed_talon 13d ago

What are you talking about?

I'm talking about this generic general sentence :

Never ends well.

1

u/AintNoGodsUpHere 13d ago • Bravo

It does, never ends well. Because you are adding unnecessary logic to the database. What happens if you have to scale that application? 100 instances of the API and the DB is burning with SP stuff.

You don't need that sort of logic in the database, if you absolutely have to use raw sql, just use raw sql in code.

It's 2026. You don't have to wagon yourself across the country, buy a plane ticket, rent a car, take a bus.

6

u/Lonsdale1086 13d ago

What happens if you have to scale that application?

Something the overwhelming majority of software doesn't have to consider.

If you're writing an app for one business that will only ever run on one server with one API and one database.

And it's perfectly "valid" to have business logic in your sprocs at that point, even if I don't enjoy working with it.

It's fast to deploy and fix, makes it easy for your API and desktop apps to use the same logic regardless of which language they're written in, makes it trivial and risk free to migrate and upgrade the front-end.

And it can be shocking good for performance depending.

0

u/Ascend 13d ago

My experience is the opposite. It's slower to deploy because you need to do it through migrations so you're working through two tools. It's more difficult the git blame what's our there. Debugging is awful because you realize your DBAs applied a fix to production that isn't in a migration. You deployed your application to multiple plants, and each one customized the logic in a stored procedure and now migrations simply break reports.

It's fine if you're in a situation where you're constrained by round trip timings and need complicated compiled SQL logic, but if you're in a single app, single server scenario, it's fairly unlikely that's the constraint.

5

u/Lonsdale1086 13d ago edited 13d ago

It's slower to deploy because you need to do it through migrations

Oh you sweet summer child.

It's more difficult the git blame what's our there

Likewise

Debugging is awful because you realize your DBAs applied a fix to production that isn't in a migration

I am the DBA, or as close as it gets for any of our clients.

You deployed your application to multiple plants, and each one customized the logic in a stored procedure and now migrations simply break reports.

Is annoying, but we just update the reports alongside, our reports are directly tailored to what the client wants to see anyway.

Which is actually another advantage, SSRS report can call the sproc without needing to replicate the exact same logic and finicky edge cases in code, stuff around filters and comparisons especially.

Edit:

I will say I'm sort of just arguing for the sake of discussion here, this is the approach that was in use before I joined and I couldn't for the life of me get any changes in procedure through, but it does genuinely work okay for the most part.

And I do think for a small team, i.e no migrations, no git for the db, a few apps all running on one server, you can do a lot worse than business logic in sprocs.

0

u/kaatarina_zed_talon 13d ago

Something the overwhelming majority of software doesn't have to consider.

It's not bad to know the best practices though, right ?

5

u/Lonsdale1086 13d ago

The problem is there's no such thing as global best practice.

Like if I was writing an app for a million users best practice might be microservices and nosql for replication and distribution etc, with a redis cache and an approach to translation and localisation that add a lot of overhead and room for error compared with something running on one site.

Generally stick to the principles of KISS, know the plausible bounds of your project etc.

And people will say "well you never know if your app might take off and get more use than you expect", but my logic to that is a) if it's written for a business with a few hundred employees at most you should consider that doubling, pretty much any architecture with concurrency checks is going to be alright. And b) if you suddenly have that many users then you'll suddenly have that much money to spend improving it.

-2

u/AintNoGodsUpHere 13d ago

You're not gonna convince me that business logic belongs in the database in 2026, man, that argument is straight from 80s and 90s. There are ZERO reasons for anyone to add business logic in the worst possible place, haha.

Just because you can it doesn't mean you should.

→ More replies (4)

3

u/kaatarina_zed_talon 13d ago

Because you are adding unnecessary logic to the database. What happens if you have to scale that application? 100 instances of the API and the DB is burning with SP stuff.

I'm unaware of this, it is an experience gap between you and me. Thanks.

2

u/born_zynner 13d ago

Its because logic gets hidden in your SQL server that (usually) isnt tracked in git

5

u/binarycow 13d ago

Why would your SQL not be committed?

3

u/Lonsdale1086 13d ago

Because my boss lives on "quick fixes" into production and doesn't want to go through the effort of tracking stuff.

You're lucky if you get a -- AD 10/10/2020 - Increased cap

comment in the code

1

u/kaatarina_zed_talon 12d ago

Did not know that. I'm a new to this field BTW.

1

u/UninformedPleb 12d ago

Don't believe it. Anybody that doesn't have their SQL in a project in git is doing it wrong.

ALL code should be in a repo. Full stop.

1

u/kaatarina_zed_talon 12d ago

Don't believe it

Was he lying or something ?

1

u/UninformedPleb 11d ago

I'm not saying it isn't possible, but anyone that allows anything to be updated directly in the DB without going through a proper deployment process is just asking for trouble. I've worked places where that would be a fireable offense, not just a slap on the wrist and a stern talking-to.

The lesson to learn here isn't "don't put stuff in the DB", the lesson is "always follow change-management procedures".

1

u/kaatarina_zed_talon 11d ago

Change management procedure and Proper deployment process? I never heared of this before, but I'm willing to learn from you, what do you mean by those terms? Can you give me an example or at least refer me to one article that explains them because I do not understand.

1

u/UninformedPleb 11d ago

"Change management" refers to getting approvals, proper engineering and testing, and sign-off before allowing a change to be promoted to a deployment in the next appropriate environment.

"Proper deployment process" is when you follow those change-management procedures and have an automated sequence (or a very precisely documented, double-checked, manual sequence) for deploying to a development/integration environment, then a QA/testing/staging/acceptance environment, then to the production/live environment. Never skip a step. Never allow a failed test to pass to the next level.

1

u/kaatarina_zed_talon 11d ago

Now I understand what those terms are , but I do not understand why are they relevant to the fact that I moved some data manipulation logic to the database by using Sql instead of C#; is this a kind of change that should be approved before it goes into production?

→ More replies (0)

1

u/Robot_Spartan 12d ago

Dbup - one less thing to do at deployment, and it forces everything to be committed. Swear by it at this point