Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

SqlEngine - C#

RSS
Modified on Thu, Jun 18, 2020, 12:30 PM by Administrator Categorized as ·Net Framework

Notes

Recommend placing this class in your DAL project's "Seed" folder (for EF6).

Code

using System.IO;
using System.Linq;
using System.Reflection;
public static class SqlEngine
{
    /// <summary>
    /// Executes a SQL script file within the ACME.DAL project's SqlCode folder.  The SQL script CANNOT contain a "GO" command.
    /// Best practice is to start each SQL file with "CREATE OR ALTER" -- for example "CREATE OR ALTER FUNCTION dbo.PadLeft".
    /// </summary>
    /// <param name="db"></param>
    /// <param name="fileName">Relative path of SQL script file, relative to "ACME.DAL\SeedSql"</param>
    public static void ExecuteSqlScript(DentaCadDataModel db, string fileName)
    {
        var entryPath = Assembly.GetExecutingAssembly().Location;
        var items = entryPath.Split(new[] { '\\' });
        var parentPath = string.Join("\\", items.Take(items.Length - 4));
        var absFileName = Path.Combine(parentPath, @"ACME.DAL\SqlCode", fileName);

        if (!File.Exists(absFileName))
            throw new FileNotFoundException($"SQL Script '{absFileName}' not found");

        var sql = File.ReadAllText(absFileName);
        db.Database.ExecuteSqlCommand(sql);
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.