.Net code first migration reflection issues - c#

When running Update-Database in the package manager console of my solution, I receive the following error:
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindType[TBase](String typeName, Func`2 filter, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
I read in other similar stack overflow discussions that sometimes more information can be gained by running the update programatically and catching that exception, so I have tried this:
static void Main(string[] args)
{
//https://stackoverflow.com/questions/15774247/how-to-debug-entity-framework-migration-loaderexceptions
DbMigrator migrator = new DbMigrator(new Configuration());
migrator.Update();
}
The above code actually runs the update successfully without issues (as do the migrations when run by the web browser on application initialization) but the package manager still fails on the same Update-Database command with the same error. I've checked startup projects, default projects, reference copy-local settings, regenerating the ibmmx file, database restores, and run multiple visual studio/OS restarts. I've also tried accessing the exception information through powershell but haven't found anything. Does anyone know of a way to get more information about why the package manager operations are failing?
This same setup with the same underlying database states (different database servers, both on localhost) works without issues on another development machine, so it appears to be something specific to my setup or installation. Are there any other "gotchas" I should be aware of?
Thanks.
Update: I might have spoken too soon about the migrations working outside of the package manager. I just made one on the working dev machine, pulled it to my local machine, and found it doesn't work through the application initialization in the web browser or the package manager.

Related

ssis package execution succeeds directly but fails via c# code

I have the following code which seems to works OK for executing an SSIS package from c# BUT every time the variable "Resp" returns a Failure even if the package passes when I execute it directly in SSIS.
Again, the package contains a Script component that writes to an SQL server table. All that works OK when the package is executed directly in SSIS but nothing happens when the same package is called via C# with the code below. I cant work out what I am doing wrong. help!
string packageLocation = #"c:\packageLocationPath";
Package pkg;
Application app;
app = new Application();
pkg = app.LoadPackage(packageLocation, null);
var Resp = pkg.Execute();
Detecting error
First you have to read the errors raised by the package. There are two options to detect these errors:
(1) loop over errors
You can loop over the package errors by accessing Errors property. As example:
if(p.Errors.Count > 0){
foreach(DtsError err in p.Errors){
Messagebox.Show(err.Description);
}
}
More information at:
How to get all errors of all SSIS packages in a solution
(2) Enable logging from package
You can capture all errors, warning and information from a package by enabling logging option:
Add and configure logging
Possible failure causes
Make sure that if you are using windows authentication to connect to SQL, that the user account used to execute the application via C# is granted to make a connection.
If the package is accessing a file system, make sure that the user has the required permissions to access these files

ASP.NET Core 2 Migrations don't work on new machine with empty database

I created a ASP.NET Core 2 project, created some migrations along the way, and pushed the code up to a repository.
Today, I pulled the code to another computer I have for development, the database was obviously not created on the new machine so I created a empty database locally to match the connection string.
Now, when trying to run the code "dotnet ef database update" I get this error:
An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Invalid object name 'AspNetUsers'.)
Unable to create an object of type 'AppDbContext'. Add an
implementation of 'IDesignTimeDbContextFactory' to the
project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
Please keep in mind that any "dotnet ef" command I run I have the same error, I tried deleting all the migrations and creating a new one using the "dotnet ef migrations add InitialDb" command, but I still get this error.
I am using Identity in my project and I believe it has to do with this error: (Invalid object name 'AspNetUsers'.)
The commands run without any problem on the machine I initially started to develop the application.
I tried Update-Database from PM with the same result.
Here is an image illustrating the problem:
Thanks in advance.
I found the problem, I had a seeder in the Startup class that was seeding an admin user in case it did not exist.
Because the table did not exist the seeder was failing on each command because it was in the Startup class and was executing all the time.
This issue can be closed.

Entity: automatic migration on Production not working

I have looked at other questions on SO and on blogs and official MS docs but I can't find the proper way.
What I am trying to achieve:
Deploy version 1 of an MVC website with SQL DB (code is based on Entity Code First v. 6.1), without any concept of migration because it's DB SCHEMA v.1
Deploy further versions (2, 3, ..) with automatic migration to SCHEMA v2 (and then v3 etc.) and without running Update-Database in Package Manager console
So, following MS tutorial (i.e. https://msdn.microsoft.com/en-gb/data/jj591621.aspx) version 1 creates tables for Schema v1:
Blogs table with two columns (BlogId and Name)
__MigrationHistory with one row (MigrationId contains InitialCreate). Not sure what this is about, but I guess it's the initial schema. Am I right?
Then I open Package Manager Console and I type: Enable-Migrations which creates classes for migration (201610091823367_InitialCreate.cs and Configuration.cs). I then modify the Blog class to have a new property Url as suggested in the tutorial and run Add-Migration AddBlogUrl, which creates 201610091830008_AddBlogUrl.cs
In addition, I added
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
to the main, so when the application starts it should migrate automatically.
I launch the app v2, and everything is working perfectly. The Table has now the new column.
When I launch the app v2 again, it crashes with exception:
Unhandled exception: System.Data.SqlClient.SqlException: There is already an object named 'Blogs' in the database. and all the related stack trace.
So it looks like it's not recognizing that it's in the DB there's the most recent schema, so it tries to create the table again. I have added a breakpoint to InitialCreate class, method Up and it is called. I am surprised!
I've tried also a different approach:
ran app v1
ran app v2b with AutomaticMigrationsEnabled = true; in the Configuration class. The outcome is the same.
Can anyone help me to understand what's wrong and what's the right approach?
Can you confirm that in the meantime I am OK to deploy SCHEMA v1 without having enabled migrations at all?
I was hoping that this kind of scenarios were covered by Entity.

Powershell fails to find its dll or dependency in VS 2013 Package Manager Console

I'm using VS Express 2013 .Net 4.5. I'm designing in MVC5 and EF6 with MS SQLServer LocalDB in an Oracle VirtualBox Windows 7 64bit client.
I am trying to apply SQL Server LocalDb migrations with the command:
PM> Enable-Migrations -ContextTypeName SGHWA_MVC.Models.Context
This always fails.
My limited web knowledge is with Web Forms so I am completely new to MVC and EF. Also I have never used PMC and Powershell. I have searched for solutions but have not found questions similar to this error that Package Manager Console produces.
First there is a warning:-
Cannot determine a valid start-up project. Using project 'SGHWA_MVC' instead. Your configuration file and working directory may not be set as expected. Use the -StartUpProjectName parameter to set one explicitly. Use the -Verbose switch for more information.
PCM drop-down box shows the Default project correctly as SGHWA_MVC. The solution property pages show this one project as the start-up project.
I went to http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference but could not see the -StartUpProjectName parameter mentioned. I'm not sure to which command this parameter applies.
Then the first error appears:-
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly 'file://\W7O2007\Users\Admin\Documents\Visual Studio 2013\Projects\SGHWA_MVC\packages\EntityFramework.6.1.0\tools\EntityFramework.PowerShell.Utility.dll' or one of its dependencies. Operation is not supported.
(Exception from HRESULT: 0x80131515)"At \W7O2007\Users\Admin\Documents\Visual Studio 2013\Projects\SGHWA_MVC\packages\EntityFramework.6.1.0\tools\EntityFramework.psm1:780 char:62
+ $utilityAssembly = [System.Reflection.Assembly]::LoadFrom <<<< ((Join-Path $ToolsPath EntityFramework.PowerShell.Utility.dll))
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
It suggests the file is not there to be loaded but it does exist on the PC at the path shown. I suspect it is the Join-Path that fails but am unsure how to test this.
The packages.config files has a line:-
(leading < removed) package id="Powershell.Deployment" version="1.1.0.0" targetFramework="net45" />
My research shows it could be permissions, remote access, that the Project Build should have Generate Serialization Assembly as 'On', 'Off' or 'Auto' or even NuGet packages that cause this but I cannot determine if it is a PMC, NuGet, Powershell or Windows problem.
Two more error messages appear relating to similar problems in EntityFramework.psm1 and seem to be related to this first problem.
Please can anyone advise the likely cause and guide me through what/how to test and solve this?
I realize this is an old thread, but I just ran into this problem using a newly-installed copy of Microsoft Visual Studio 2015 Enterprise with Update 1.
My solution was to delete this folder:
C:\Users\\(my user ID)\\.nuget\packages\EntityFramework\6.1.3
and allow it to be regenerated the next time the Entity Framework is added to a project. Originally, the PowerShell DLL's were missing from this folder. Strange.
Your question has several parts.
First, you cannot find the documentation, and you have it at your fingertips:
Update-Database -?
Then, you can read at the bottom of this help:
TO see the examples, type: "get-help Update-Database -examples".
For more information, type: "get-help Update-Database -detailed".
For technical information, type: "get-help Update-Database -full".
Second, -StartupProjectName is required to find the configuration file that has the required connection string (you also specify the connection directly using another options) NOTE: This has nothing to do with the solution's startup project
And, if having this clear doesn't solve the problem, try uninstalling and reinstalling the EntityFramework package (in case something went wrong). Take into account that, if you have several projects, it's possible that you need to do this for all the affected projects. You can do this more easily using the Manage Nuget Packages for Solution... menu option.
Edit
(Added to help choose the right Default project in Package Manager Console or specify -ProjectName).
I forgot to answer the most important part of the question: for Migrations commands to work, it's necessary to run them on a project that references the EF assemblies. This solves the missing assembly problem.
In this case it's clear that the chosen StartUpProject, which is the Web App have the connection strings, but doesn't have a reference to EF. That's why running the command fails. And most probably the command is being run with this as the default project in the console.
To solve this, you need to run Migrations within a project which has references to EF, and it will work flawlessly: choose that project in the drop down list named "Default project" on the top bar of the Package Manager Console.
This can also be done by specifying the -ProjectName option, which must point to the project containing the Migration configuration class, and thus, have also the reference to EF. NOTE: you must also sepcify the -ConfigurationTypeName param if you have several migrations for several contexts, as supported from EF 6.

How do I run an SSIS package in SqlServer 2012 using vs2010?

Setup
I have a vs2010 SSIS package that I can run from visual studio. I have deployed it to my local 2012 server, and I can also execute that package from SSMS. In SSMS, I see the package here:
\Integration Services Catalogs\SSISDB\DAT_Load\Projects\UploadSYS.dtsx
Note: vs2010 does not give me an option to deploy a package anywhere but in a server, and then only in Integration Services Catalogs. Once in there, the MSDB database does not have an entry in the sysssispackages table.
Previously, it was adequate to bring up SSMS and run the package from there(right-click & execute). Now, I have to execute this from a C# web application. Furthermore, I need to trap progress messages and such through events.
Effort
I was able to determine how to set up the event trapping and I got myself to the point where I should have been able to execute the package from code:
public DTSExecResult ExecutePackage(string packageName, HttpContextBase context)
{
string ppath = ConfigurationManager.AppSettings[packageName + "Package"];
string pserv = ConfigurationManager.AppSettings[packageName + "Server"];
string puser = ConfigurationManager.AppSettings[packageName + "User"];
string ppass = ConfigurationManager.AppSettings[packageName + "Pwd"];
_context = context;
_pkgLocation = "";
_app = new Application();
_pkg = _app.LoadFromSqlServer(ppath, pserv, puser, ppass, _SSISEvents);
_pkgResults = _pkg.Execute(_connections, _variables, _SSISEvents, _log, null);
return _pkgResults;
}
Problem
I cannot locate the package. When I reach the LoadFromSqlServer statement, I receive an error that says:
Cannot find folder "\Integration Services Catalogs\SSISDB\DAT_Load\Projects\UploadSYS.dtsx"
The same thing happens for variations in the path (variable = ppath):
\Integration Services Catalogs\SSISDB\DAT_Load\Projects\UploadSYS.dtsx
\SSISDB\DAT_Load\Projects\UploadSYS.dtsx
\DAT_Load\Projects\UploadSYS.dtsx
etc.
Running this from the command line or a stored procedure is not an option.
So, can anyone tell what I am missing here? Does the Application object need to initialize something? Is this even possible?
Taking another bite at the problem but see Set SSIS database package path and SSIS Organization for background reading.
Until SSIS 2012, if packages were deployed to SQL Server, they lived in the msdb. The .NET API for interacting with them was the same across versions.
With the 2012 release of SSIS, we have two different deployment models. Package deployment, which is the "classic" model is alive and fully supported. The same code for running a package on 2005 will work for 2012 package deployment model projects. This is the Microsoft.SqlServer.Dts.Runtime Namespace
Your code is attempting to load a 2012 solution built using the "project deployment model" with the "package deployment model" API. This is the Microsoft.SqlServer.Management.IntegrationServices Namespace and the two don't mix.
Your options are to switch your project back to the Package deployment model or update your code. In the first linked question, I provided the VB.NET implementation for running an SSIS package in the SSISDB catalog. There is some way of running a .ispac file because I see the option in dtexec but I'm not seeing the specific method. This is mechanism VS/SSDT uses when it runs the packages locally.

Categories