create a method that uses dapper to call a sql script referenced as an embedded resource in csharp

Here's an example code snippet that shows how to create a method using Dapper to call a SQL script referenced as an embedded resource in C#:

main.cs
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using Dapper;

public static class SqlScriptRunner
{
    public static void RunScript(string scriptName, IDbConnection connection)
    {
        var assembly = Assembly.GetExecutingAssembly();
        
        using (var stream = assembly.GetManifestResourceStream(scriptName))
        {
            if (stream == null)
            {
                throw new ArgumentException($"The script '{scriptName}' was not found as an embedded resource.");
            }

            string script;
            using (var reader = new System.IO.StreamReader(stream))
            {
                script = reader.ReadToEnd();
            }

            connection.Execute(script);
        }
    }
}
763 chars
29 lines

To use this method, you would provide the name of the embedded resource that contains the SQL script you want to run, as well as an open IDbConnection object that will be used to execute the script. For example:

main.cs
using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    SqlScriptRunner.RunScript("MyAssemblyName.MyScript.sql", connection);
}
162 chars
6 lines

Note that the scriptName parameter should be the full name of the embedded resource, which includes the namespace and assembly name. You can find this value by opening the Properties window for the file in Visual Studio and copying the value from the "Full Name" field.

gistlibby LogSnag