Created
May 7, 2020 01:38
-
-
Save StefanRiedmann/ab151973be5f1f28d92bb75fb9eaeed9 to your computer and use it in GitHub Desktop.
Entity Framework Core preparing schema and views
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (var db = new GardenContext()) | |
{ | |
db.Database.Migrate(); | |
CreateViews(db.Database); | |
} | |
} | |
private static void CreateViews(DatabaseFacade db) | |
{ | |
InjectView(db, "GardenInfo.sql", "View_GardenInfos"); | |
} | |
private static void InjectView(DatabaseFacade db, string sqlFileName, string viewName) | |
{ | |
var assembly = typeof(Program).Assembly; | |
var assemblyName = assembly.FullName.Substring(0, assembly.FullName.IndexOf(',')); | |
var resource = assembly.GetManifestResourceStream($"{assemblyName}.{sqlFileName}"); | |
var sqlQuery = new StreamReader(resource).ReadToEnd(); | |
//we always delete the old view, in case the sql query has changed | |
db.ExecuteSqlRaw($"IF OBJECT_ID('{viewName}') IS NOT NULL BEGIN DROP VIEW {viewName} END"); | |
//creating a view based on the sql query | |
db.ExecuteSqlRaw($"CREATE VIEW {viewName} AS {sqlQuery}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment