dotnet ef migrations add: create migration file only if there are changes - entity-framework-core

I'm using dotnet ef migrations add {MigrationName} in order to create a new migration.
In case there are no Entities/Context changes this creates a migration with empty Up(MigrationBuilder migrationBuilder) and Down(MigrationBuilder migrationBuilder) functions.
Is there a way for the migrations add command to skip the creation of 'empty' files?
Alternatively, Is there a way to detect if there are changes before running the migrations add command?

I found a solution to this problem.
There is a way to create migrations programmatically instead of using CLI.
After looking at the MigrationsScaffolder source code I managed to modify the code in the first link in order to support my needs:
using (var db = new MyDbContext())
{
var reporter = new OperationReporter(
new OperationReportHandler(
m => Console.WriteLine(" error: " + m),
m => Console.WriteLine(" warn: " + m),
m => Console.WriteLine(" info: " + m),
m => Console.WriteLine("verbose: " + m)));
var designTimeServices = new ServiceCollection()
.AddSingleton(db.GetService<IHistoryRepository>())
.AddSingleton(db.GetService<IMigrationsIdGenerator>())
.AddSingleton(db.GetService<IMigrationsModelDiffer>())
.AddSingleton(db.GetService<IMigrationsAssembly>())
.AddSingleton(db.Model)
.AddSingleton(db.GetService<ICurrentDbContext>())
.AddSingleton(db.GetService<IDatabaseProvider>())
.AddSingleton<MigrationsCodeGeneratorDependencies>()
.AddSingleton<ICSharpHelper, CSharpHelper>()
.AddSingleton<CSharpMigrationOperationGeneratorDependencies>()
.AddSingleton<ICSharpMigrationOperationGenerator, CSharpMigrationOperationGenerator>()
.AddSingleton<CSharpSnapshotGeneratorDependencies>()
.AddSingleton<ICSharpSnapshotGenerator, CSharpSnapshotGenerator>()
.AddSingleton<CSharpMigrationsGeneratorDependencies>()
.AddSingleton<IMigrationsCodeGenerator, CSharpMigrationsGenerator>()
.AddSingleton<IOperationReporter>(reporter)
.AddSingleton<MigrationsScaffolderDependencies>()
.AddSingleton<ISnapshotModelProcessor, SnapshotModelProcessor>()
.AddSingleton<MigrationsScaffolder>()
.BuildServiceProvider();
var scaffolderDependencies = designTimeServices.GetRequiredService<MigrationsScaffolderDependencies>();
var modelSnapshot = scaffolderDependencies.MigrationsAssembly.ModelSnapshot;
var lastModel = scaffolderDependencies.SnapshotModelProcessor.Process(modelSnapshot?.Model);
var upOperations = scaffolderDependencies.MigrationsModelDiffer.GetDifferences(lastModel, scaffolderDependencies.Model);
var downOperations = upOperations.Any() ? scaffolderDependencies.MigrationsModelDiffer.GetDifferences(scaffolderDependencies.Model, lastModel) : new List<MigrationOperation>();
if (upOperations.Count() > 0 || downOperations.Count() > 0)
{
var scaffolder = designTimeServices.GetRequiredService<MigrationsScaffolder>();
var migration = scaffolder.ScaffoldMigration(
"MyMigration",
"MyApp.Data");
File.WriteAllText(
migration.MigrationId + migration.FileExtension,
migration.MigrationCode);
File.WriteAllText(
migration.MigrationId + ".Designer" + migration.FileExtension,
migration.MetadataCode);
File.WriteAllText(migration.SnapshotName + migration.FileExtension,
migration.SnapshotCode);
}
}

I don't know if its possible at all, But empty migrations are helpful also like if you want to run any script manually, for example, create/alter StoredProcedures/Trigger. For this purpose, you can generate an empty migration exclusively for a particular purpose.

Related

Executing stored procedures and getting the output

I am trying to read the size of my database, and I can do this in SQL Server - but how do I run the following code in Entity Framework and get the output?
USE Impro_V2
GO
sp_spaceused
GO
or
EXEC sp_helpdb N'Impro_V2';
Using context.Database.ExecuteSqlCommand I get a result of "-1". I am not even sure whether that is failed.
How do run code like that?
The answer is here:
How to know the physical size of the database in Entity Framework?
The code is simple:
var ef = new MyDbContext();
var sqlConn = ef.Database.Connection as SqlConnection;
var cmd = new SqlCommand("sp_spaceused")
{
CommandType = System.Data.CommandType.StoredProcedure,
Connection = sqlConn as SqlConnection
};
var adp = new SqlDataAdapter(cmd);
var dataset = new DataSet();
sqlConn.Open();
adp.Fill(dataset);
sqlConn.Close();
// example read
foreach (DataTable table in dataset.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
console.write(row[icol].tostring());
etc

EF Code First - Create Rollback Script for First Migration

We've got a little console app that creates scripts based on to>from migrations ... we're using to do our rollback scripts as well.
With rollback we stick in null and the migration to rollback to.
We've just moved the Console app to a new solution, but I cannot get it to make the first rollback script when the is only one migration in _MigrationHistory.
Any ideas?
public static string CreateScriptBetween(string from, string to, string name)
{
var dbMigrator = new DbMigrator(new EmptyConfiguration());
var scriptor = new MigratorScriptingDecorator(dbMigrator);
var script = "USE MYCOOLSKILLZDB" + Environment.NewLine + Environment.NewLine + "GO" + Environment.NewLine
+ Environment.NewLine;
script += scriptor.ScriptUpdate(from, to);
var filename = FileGenerator.NewNamedFilename(name, "sql");
using (var writer = new StreamWriter(filename, false))
{
writer.Write(script);
}
return filename;
}

nDepend - how to modify "JustMyCode" queries using nDepend API?

My goal is to modify "JustMyCode" queries using nDepend API. I am using code like:
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
var originalQuery = justMyCodeGroup.ChildQueries
.Single(x => x.QueryString.Contains("Discard generated Types from JustMyCode"));
var changedQuery = originalQuery.Controller.CreateQuery(originalQuery.IsActive,
query,
originalQuery.
DisplayStatInReport,
originalQuery.DisplayListInReport,
originalQuery.DisplaySelectionViewInReport,
originalQuery.IsCriticalRule);
var justMyCodeGroupWithModifiedQuery = justMyCodeGroup.ReplaceQuery(originalQuery, changedQuery);
prj.CodeQueries.CodeQueriesSet.ReplaceGroup(justMyCodeGroup, justMyCodeGroupWithModifiedQuery);
However, when I run the code above I get ArgumentException with message:
newGroup.Controller is different than this groupOfGroups.Controller
Any help ?
Update 1:
I also tried code:
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
var originalQuery = justMyCodeGroup.ChildQueries
.Single(x => x.QueryString.Contains("Discard generated Types from JustMyCode"));
var changedQuery = originalQuery.Controller.CreateQuery(originalQuery.IsActive,
query,
originalQuery.
DisplayStatInReport,
originalQuery.DisplayListInReport,
originalQuery.DisplaySelectionViewInReport,
originalQuery.IsCriticalRule);
var justMyCodeGroupWithModifiedQuery = justMyCodeGroup.ReplaceQuery(originalQuery, changedQuery);
var newQueries = new List<IQuery>();
foreach (var q in justMyCodeGroup.ChildQueries)
{
if (q.QueryString.Contains("Discard generated Types from JustMyCode"))
{
continue;
}
newQueries.Add(prj.CodeQueries.CodeQueriesSet.Controller.CreateQuery(q.IsActive, q.QueryString,
q.DisplayStatInReport, q.DisplayListInReport, q.DisplaySelectionViewInReport, q.IsCriticalRule));
}
newQueries.Add(prj.CodeQueries.CodeQueriesSet.Controller.CreateQuery(originalQuery.IsActive, query, originalQuery.DisplayStatInReport, originalQuery.DisplayListInReport, originalQuery.DisplaySelectionViewInReport, originalQuery.IsCriticalRule));
var newGroup = prj.CodeQueries.CodeQueriesSet.Controller.CreateGroup(justMyCodeGroup.Name,
justMyCodeGroup.IsActive, justMyCodeGroup.ShownInReport, newQueries, new List<IGroup>());
prj.CodeQueries.CodeQueriesSet.RemoveGroup(justMyCodeGroup);
prj.CodeQueries.CodeQueriesSet.AddGroup(newGroup);
Right now, RemoveGroup throws exception:
this group of groups doesn't contain groupToRemove.
Update 2:
And I also wonder, why does this code return false ?
var justMyCodeGroup = prj.CodeQueries.CodeQueriesSet.ChildGroups.Single(x => x.Name.Contains("JustMyCode"));
prj.CodeQueries.CodeQueriesSet.ContainsGroup(justMyCodeGroup)
Refer to the PowerTools source file:
$NDependInstallDir$\NDepend.PowerTools.SourceCode\CQL2CQLinq\CQL2CQLinqPowerTool.cs
This PowerTools convert code queries written with old CQL syntax into code queries written with new CQLinq syntax, hence it loads the queries set from a project, update CQL queries, and then save the new queries set in the project.
The queriesController is gathered this way...
var queriesSet = project.CodeQueries.CodeQueriesSet;
var queriesController = queriesSet.Controller;
... and then used this way to modify the queries set:
queriesController.DoUpdateQueryObject(query, newQuery);

How do I use MigratorScriptingDecorator in Entity Framework code first?

I have problems using the MigratorScriptingDecorator.ScriptUpdate in Entity Framework 4.3.1.
When specifying sourceMigration and targetMigration only my initial migration gets written, the rest of my migrations become empty.
I have entered a bug report on Microsoft Connect containing reproducing code.
https://connect.microsoft.com/VisualStudio/feedback/details/731111/migratorscriptingdecorator-in-entity-framework-migrations-does-not-respect-sourcemigration-and-targetmigration
I expect MigratorScriptingDecorator.ScriptUpdate("from", "to") to behave exactly like the corresponding PM command
PM> Update-Database -Script -SourceMigration from -TargetMigration to
Should ScriptUpdate be equivalent to Update-Database -Script?
Are there any other ways of generating update scripts from code?
As noted on the linked Microsoft Connect issue the problem was a reuse of the same DbMigrator on several MigratorScriptingDecorators.
The original code was
DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
var sql = new MigratorScriptingDecorator(efMigrator).ScriptUpdate(migration.Item1, migration.Item2); // <-- problem here, the efMigrator is reused several times
Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
Console.WriteLine(sql);
Console.WriteLine("-------------------------------------");
}
the MigratorScriptingDecorator should be instantiated outside the loop like this:
DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
var scriptMigrator = new MigratorScriptingDecorator(efMigrator); // <-- now only one MigratorScriptingDecorator is created for the DbMigrator
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
var sql = scriptMigrator.ScriptUpdate(migration.Item1, migration.Item2);
Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
Console.WriteLine(sql);
Console.WriteLine("-------------------------------------");
}

Changing schema name on runtime - Entity Framework

I need to change the storage schema of the entities on runtime.
I've followed a wonderful post, available here:
http://blogs.microsoft.co.il/blogs/idof/archive/2008/08/22/change-entity-framework-storage-db-schema-in-runtime.aspx?CommentPosted=true#commentmessage
This works perfectly, but only for queries, not for modifications.
Any idea why?
Well, I was looking for this piece of code all around the Internet. In the end I had to do it myself. It's based on Brandon Haynes adapter, but this function is all you need to change the schema on runtime - and you don't need to replace the autogenerated context constructors.
public static EntityConnection Create(
string schema, string connString, string model)
{
XmlReader[] conceptualReader = new XmlReader[]
{
XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".csdl")
)
};
XmlReader[] mappingReader = new XmlReader[]
{
XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".msl")
)
};
var storageReader = XmlReader.Create(
Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(model + ".ssdl")
);
XNamespace storageNS = "http://schemas.microsoft.com/ado/2009/02/edm/ssdl";
var storageXml = XElement.Load(storageReader);
foreach (var entitySet in storageXml.Descendants(storageNS + "EntitySet"))
{
var schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault();
if (schemaAttribute != null)
{
schemaAttribute.SetValue(schema);
}
}
storageXml.CreateReader();
StoreItemCollection storageCollection =
new StoreItemCollection(
new XmlReader[] { storageXml.CreateReader() }
);
EdmItemCollection conceptualCollection = new EdmItemCollection(conceptualReader);
StorageMappingItemCollection mappingCollection =
new StorageMappingItemCollection(
conceptualCollection, storageCollection, mappingReader
);
var workspace = new MetadataWorkspace();
workspace.RegisterItemCollection(conceptualCollection);
workspace.RegisterItemCollection(storageCollection);
workspace.RegisterItemCollection(mappingCollection);
var connectionData = new EntityConnectionStringBuilder(connString);
var connection = DbProviderFactories
.GetFactory(connectionData.Provider)
.CreateConnection();
connection.ConnectionString = connectionData.ProviderConnectionString;
return new EntityConnection(workspace, connection);
}
The resulting EntityConnection should be passed as a parameter when instantiating the context. You can modify it, so all ssdl models are modified by this function, not only the specified one.
I've managed to resolve this issue by using a brilliant library, located in CodePlex (courtesy of Brandon Haynes), named "Entity Framework Runtime Model Adapter", available here:
http://efmodeladapter.codeplex.com/
I've tweaked it a bit, to fit our needs and without the need of replacing the designer code at all.
So, I'm good.
Thanks anyways, and especially to Brandon, amazing job!
I need import data from postgres database. It by default use schema "public". So I use Entity Framework CTP 4 "Code first". It by default use schema "dbo". To change it in runtime I use:
public class PublicSchemaContext : DbContext
{
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder builder)
{
builder.Entity<series_categories>().MapSingleType().ToTable("[public].[series_categories]");
}
public DbSet<series_categories> series_categories { get; set; }
}
It work for select, insert, update and delete data. So next test in pass:
[Test]
public void AccessToPublicSchema()
{
// Select
var db = new PublicSchemaContext();
var list = db.series_categories.ToList();
Assert.Greater(list.Count, 0);
Assert.IsNotNull(list.First().series_category);
// Delete
foreach (var item in db.series_categories.Where(c => c.series_category == "Test"))
db.series_categories.Remove(item);
db.SaveChanges();
// Insert
db.series_categories.Add(new series_categories { series_category = "Test", series_metacategory_id = 1 });
db.SaveChanges();
// Update
var test = db.series_categories.Single(c => c.series_category == "Test");
test.series_category = "Test2";
db.SaveChanges();
// Delete
foreach (var item in db.series_categories.Where(c => c.series_category == "Test2"))
db.series_categories.Remove(item);
db.SaveChanges();
}
Not an answer per se but a followup on Jan Matousek's Create[EntityConnection] method showing how to use from a DbContext. Note DB is the DbContext type passed to the generic repository.
public TxRepository(bool pUseTracking, string pServer, string pDatabase, string pSchema="dbo")
{
// make our own EF database connection string using server and database names
string lConnectionString = BuildEFConnectionString(pServer, pDatabase);
// do nothing special for dbo as that is the default
if (pSchema == "dbo")
{
// supply dbcontext with our connection string
mDbContext = Activator.CreateInstance(typeof(DB), lConnectionString) as DB;
}
else // change the schema in the edmx file before we use it!
{
// Create an EntityConnection and use that to create an ObjectContext,
// then that to create a DbContext with a different default schema from that specified for the edmx file.
// This allows us to have parallel tables in the database that we can make available using either schema or synonym renames.
var lEntityConnection = CreateEntityConnection(pSchema, lConnectionString, "TxData");
// create regular ObjectContext
ObjectContext lObjectContext = new ObjectContext(lEntityConnection);
// create a DbContext from an existing ObjectContext
mDbContext = Activator.CreateInstance(typeof(DB), lObjectContext, true) as DB;
}
// finish EF setup
SetupAndOpen(pUseTracking);
}
I was able to convert the solution from Jan Matousek to work in vb.net 2013 with entity framework 6. I will also try to explain how to use the code in vb.net.
We have a JD Edwards Database which uses different Schema's for each environment (TESTDTA, CRPDTA, PRODDTA). This makes switching between environments cumbersome as you have to manually modify the .edmx file if you want to change environments.
First step is to create a partial class that allows you to pass a value to the constructor of your entities, by default it uses the values from your config file.
Partial Public Class JDE_Entities
Public Sub New(ByVal myObjectContext As ObjectContext)
MyBase.New(myObjectContext, True)
End Sub
End Class
Next create the function that will modify your store schema .ssdl file in memory.
Public Function CreateObjectContext(ByVal schema As String, ByVal connString As String, ByVal model As String) As ObjectContext
Dim myEntityConnection As EntityConnection = Nothing
Try
Dim conceptualReader As XmlReader = XmlReader.Create(Me.GetType().Assembly.GetManifestResourceStream(model + ".csdl"))
Dim mappingReader As XmlReader = XmlReader.Create(Me.GetType().Assembly.GetManifestResourceStream(model + ".msl"))
Dim storageReader As XmlReader = XmlReader.Create(Me.GetType().Assembly.GetManifestResourceStream(model + ".ssdl"))
Dim storageNS As XNamespace = "http://schemas.microsoft.com/ado/2009/11/edm/ssdl"
Dim storageXml = XDocument.Load(storageReader)
Dim conceptualXml = XDocument.Load(conceptualReader)
Dim mappingXml = XDocument.Load(mappingReader)
For Each myItem As XElement In storageXml.Descendants(storageNS + "EntitySet")
Dim schemaAttribute = myItem.Attributes("Schema").FirstOrDefault
If schemaAttribute IsNot Nothing Then
schemaAttribute.SetValue(schema)
End If
Next
storageXml.Save("storage.ssdl")
conceptualXml.Save("storage.csdl")
mappingXml.Save("storage.msl")
Dim storageCollection As StoreItemCollection = New StoreItemCollection("storage.ssdl")
Dim conceptualCollection As EdmItemCollection = New EdmItemCollection("storage.csdl")
Dim mappingCollection As StorageMappingItemCollection = New StorageMappingItemCollection(conceptualCollection, storageCollection, "storage.msl")
Dim workspace = New MetadataWorkspace()
workspace.RegisterItemCollection(conceptualCollection)
workspace.RegisterItemCollection(storageCollection)
workspace.RegisterItemCollection(mappingCollection)
Dim connectionData = New EntityConnectionStringBuilder(connString)
Dim connection = DbProviderFactories.GetFactory(connectionData.Provider).CreateConnection()
connection.ConnectionString = connectionData.ProviderConnectionString
myEntityConnection = New EntityConnection(workspace, connection)
Return New ObjectContext(myEntityConnection)
Catch ex As Exception
End Try
End Function
Make sure that the storageNS namespace hardcoded value matches the one used in your code, you can view this by debugging the code and examining the storageXML variable to see what was actually used.
Now you can pass a new schema name, and different database connection info at runtime when you create your entities. No more manual .edmx changes required.
Using Context As New JDE_Entities(CreateObjectContext("NewSchemaNameHere", ConnectionString_EntityFramework("ServerName", "DatabaseName", "UserName", "Password"), "JDE_Model"))
Dim myWO = From a In Context.F4801 Where a.WADOCO = 400100
If myWO IsNot Nothing Then
For Each r In myWO
Me.Label1.Text = r.WADL01
Next
End If
End Using
These were the .net libraries used:
Imports System.Data.Entity.Core.EntityClient
Imports System.Xml
Imports System.Data.Common
Imports System.Data.Entity.Core.Metadata.Edm
Imports System.Reflection
Imports System.Data.Entity.Core.Mapping
Imports System.Data.Entity.Core.Objects
Imports System.Data.Linq
Imports System.Xml.Linq
Hope that helps anyone out there with the same issues.
I had a lot of problems getting this to work when using EF6 with an OData Data Service, so I had to find an alternate solution. In my case, I didn't really need to do it on the fly. I could get away with changing the schema when deploying to some test environments, and in the installer.
Use Mono.Cecil to rewrite the embedded .ssdl resources straight in the DLLs. This works just fine in my case.
Here is a simplified example of how you can do this:
var filename = "/path/to/some.dll"
var replacement = "Schema=\"new_schema\"";
var module = ModuleDefinition.ReadModule(filename);
var ssdlResources = module.Resources.Where(x => x.Name.EndsWith(".ssdl"));
foreach (var resource in ssdlResources)
{
var item = (EmbeddedResource)resource;
string rewritten;
using (var reader = new StreamReader(item.GetResourceStream()))
{
var text = reader.ReadToEnd();
rewritten = Regex.Replace(text, "Schema=\"old_schema\"", replacement);
}
var bytes = Encoding.UTF8.GetBytes(rewritten);
var newResource = new EmbeddedResource(item.Name, item.Attributes, bytes);
module.Resources.Remove(item);
module.Resources.Add(newResource);
}