Last active
August 29, 2015 14:05
-
-
Save KyleGobel/1164614ce4ade261b2e4 to your computer and use it in GitHub Desktop.
This will take an embedded .sql resource file and return it's string contents. Auto mapping dtos to sql queries that can be easily run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class SqlQueryExtensions | |
{ | |
public static string GetSqlQuery<T>(this T requestDto, Action<string> queryFilter = null, string queryNamespace = null, string filename = null) where T : class | |
{ | |
const string delimiter = "--start"; | |
var sqlStatement = string.Empty; | |
//expects the namespace of this file to be the same namespace as the sql query file | |
var namespacePart = queryNamespace ?? typeof(SqlQueryExtensions).Namespace; | |
//name is the same as the requestDto, but with a .sql extension | |
var resourceName = filename ?? (namespacePart + "." + typeof(T).Name + ".sql"); | |
using (var stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) | |
{ | |
if (stm != null) | |
{ | |
sqlStatement = new StreamReader(stm).ReadToEnd(); | |
} | |
} | |
var startIndex = sqlStatement.IndexOf(delimiter, StringComparison.CurrentCultureIgnoreCase); | |
if (startIndex > 0) | |
{ | |
return sqlStatement.Substring(startIndex + delimiter.Length); | |
} | |
if (queryFilter != null) | |
{ | |
queryFilter(sqlStatement); | |
} | |
return sqlStatement; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment