Set StartUp Project parameter for Entity Framework migrations - entity-framework

When using EF 4.3.1 migrations every time i need to add a migration or update database i have to use the StartUpProject parameter. Can I set this somewhere so I don't have to keep doing this? I don't want to set my data project as the start up project. My context and migrations are in different projects if that makes a difference.
Exception thrown when not using StartpProject parameter:
update-database -verbose
Using NuGet project 'Data.Deployment'.
Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
Exception has been thrown by the target of an invocation.

At least with Entity Framework 6, to specify the Startup Project use the -StartUpProjectName parameter with update-database:
update-database -StartUpProjectName <String>
You can use the get-help command within Package Manager Console to view possible parameters for commands:
get-help update-database -detailed

Use the StartupProject parameter: Update-database -StartupProject "PROJECTNAME"

I'm not sure if this is what you're talking about, but you can set the default project in the Package Manager Console to the project where your Migrations config resides in; it's the rightmost dropdown list.
This way I've never had to provide the startup project as an argument.

A clean way around this is to attach a Test Project to the solution.
Even if you don't want to write lots of unit tests, it's an appropriate start-up project for a data layer namespace or similar.
That makes your start up issue cleaner, the package manager applies to the whole solution IIRC - so make sure the default project is the one with the migrations folder in it.

Related

How to read a file content from EF Configuration.cs file?

I am using EF 6 Code-base migration.
I want to read the file from Configuration.cs Seed() method to insert as default data.
I am using HostingEnvironment.MapPath() as below:
string _homeContent = System.IO.File.ReadAllText( HostingEnvironment.MapPath(#"~/Data/DefaultContents/Home.html"));
But HostingEnvironment.MapPath return null value when I run the Update-database command from Package-Management Console.
Running Seed method.
System.ArgumentNullException: Value cannot be null.
Parameter name: path
at System.IO.File.ReadAllText(String path)
Kindly advise how to read the physical file from Configuration.cs Seed() method.
May I answer by myself.
Server.MapPath and HostingEnvironment.MapPath is not available in this time because HttpContext object is not ready yet.
AppDomain.CurrentDomain.BaseDirectory return "..\your project directory\bin"
E.g. C:\YourSolutionDirectory\YourProjectDirectory\bin
But we need to go up from "bin" folder, so that using Path.Combine() method and get exact file path.
string homeFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", #"Data\DefaultContents\Home.html");
Result: C:\YourSolutionDirectory\YourProjectDirectory\Data\DefaultContents\Home.html

ConfigurationType error when using Entity Framework migrate.exe with multiple migration configurations

In my solution, I have a Data project that contains multiple Entity Framework 6.1.3 migration configuration classes. My goal is to run Entity Framework migration steps - for one of them, against an existing database - from TeamCity (or, to simplify, from a command line).
The migration configuration class I am using is the following:
namespace MyProject.Data
{
public partial class MyCustomMigrationConfiguration :
DbMigrationsConfiguration<MyCustomContext>
{
public MyCustomMigrationConfiguration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = true;
MigrationsDirectory = #"Migrations\MyCustomContext\MigrationSteps";
}
}
}
I can successfully run the following command from Package Manager Console in Visual Studio:
Update-Database -Verbose -StartUpProject Web -ConnectionString '-my
connection string here-' -ConfigurationTypeName
MyCustomMigrationConfiguration -ConnectionProviderName
'System.Data.SqlClient'
I want to do the same thing from a command line, so I run this:
migrate.exe MyProject.Data.dll "MyCustomMigrationConfiguration"
/startUpConfigurationFile=MyProject.Web.dll.config
/connectionString="-my connection string here-;"
/connectionProviderName="System.Data.SqlClient" /verbose
However, I get the following error:
ERROR: The migrations configuration type
MyCustomMigrationConfiguration was not be found in the assembly
‘MyProject.Data'.
Any suggestions on how to fix this, please?
You can specify the directory where are all the dependencies (assemblies) needed to run your code. You can do that by using the /startUpDirectory option, as explained here:
Specify working directory
Migrate.exe MyApp.exe /startupConfigurationFile=”MyApp.exe.config” /startupDirectory=”c:\MyApp”
If you assembly has dependencies or reads files relative to the working directory then you will need to set startupDirectory.
Found the solution (I ended up downloading the Entity Framework source code from http://entityframework.codeplex.com/ and debugging the migrate console application).
Apparently, all the dependencies of MyProject.Data.dll need to be copied in the same folder with it and migrate.exe, otherwise the Entity Framework migrate.exe tool will throw the misleading error message above.
Entity Framework could really use better error handling and a clearer error message in this case.
As a reference to Entity Framework devs: the following code in TypeFinder.cs was returning a null type because the dependencies of MyProject.Data.dll were not copied in the folder of migrate.exe:
type = _assembly.GetType(typeName, false);

Why does custom Build Process Template executing PowerShell fail

I've modified a custom build process template to execute Powershell on the build server. This is so I can run some scripts that will automate the deployment of our SharePoint solution. Everything was working fine up until I upgraded the build servers Powershell version from 2.0 to 3.0 (which needed to be done as I was installing SCVMM Admin Console 2012 and Powershell 3.0 was a pre-requisite).
In the build template itself, I'm using a Microsoft.TeamFoundation.Build.Workflow.Activities.InvokeProcess work flow item to execute the PowerShell command with the following properties:
Arguments : String.Format(" ""& '{0}' -DropLocation '{1}' {2} "" ",
ScriptFilename, BuildDetail.DropLocation, PostDropScript2Arguments)
FileName : "powershell"
OutputEncoding :
System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.OEMCodePage)
Now every time I try to execute the build, I get the following error:
Exception Message: File not found: PowerShell (type
FileNotFoundException) Exception Stack Trace: Server stack trace:
at
Microsoft.TeamFoundation.Build.Workflow.Activities.InvokeProcess.ProcessWrapper.Start()
at
Microsoft.TeamFoundation.Build.Workflow.Activities.InvokeProcess.InvokeProcessInternal.RunCommand(AsyncState
state) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message
reqMsg, Boolean bProxyCase) at
System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed,
MessageData& msgData) at System.Func2.EndInvoke(IAsyncResult
result) at
System.Activities.AsyncCodeActivity1.System.Activities.IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext
context, IAsyncResult result) at
System.Activities.AsyncCodeActivity.CompleteAsyncCodeActivityData.CompleteAsyncCodeActivityWorkItem.Execute(ActivityExecutor
executor, BookmarkManager bookmarkManager)
Inner Exception Details:
Exception Message: The system cannot find the file specified (type
Win32Exception) Exception Stack Trace: at
System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo
startInfo) at
Microsoft.TeamFoundation.Build.Workflow.Activities.InvokeProcess.ProcessWrapper.Start()
It seems like the build is no longer able to link the "powershell" command with the actual PowerShell file.
I've manually gone onto the build server and typed "powershell" into a command line and it started PowerShell, as expected.
Has anyone else experienced this issue before?
Thanks very much
Add the full filepath to powershell.exe in the invokeprocess step in your workflow and it should always work (I would not trust the environment-settings for this)
And know, logging in on the server under your own account is not equal to the build server running under a specific account.
In my case same error occurred after deploying Windows Managment Framework 3.0.
It was solved by restarting build controller and agent.

How to Use migration with existing database?

Today EF4.3.1 released.
http://blogs.msdn.com/b/adonet/archive/2012/02/29/ef4-3-1-and-ef5-beta-1-available-on-nuget.aspx.
Follow the blog: http://thedatafarm.com/blog/data-access/using-ef-migrations-with-an-existing-database/. I firstly run:add-migration initial but throw exception as below and no create folder migrations:
PM> add-migration initial
System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.ArgumentException: 参数不正确。 (异常来自 HRESULT:0x80070057 (E_INVALIDARG))
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
在 System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
在 System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
调用的目标发生了异常。
thus, I run Enable-migrations firstly. the folder migrations with Configuration.cs created.
I checked the database, under system tables without dbo._migrationhistory table.
then I run add-migration initial again. throw the same exception Mentioned before.
the Domain model in a project and the datacontext in another project which locate in DAL layer.
in my existing database Security there are several table such as role ,user and so on.
but no migration-history table.
there is only Iset Navigators in my datacontext. no match database tables.
My problem is how to get migration-history table and set up migration?
I finally found that if move the project out of solution Folder. it will work fine. maybe it's a bug.

Running nunit-console on a solution file leads to System.IO.FileLoadException

When I try to use nunit-console.exe to run all the tests in a solution file as such:
nunit-console.exe MyProject.sln
I get the following exception (shown below). However when run the console runner on ANY of the projects in my folder structure, the runner works just fine and never gives me the following exception. I also am pretty certain that the version of the nunit library that I am linking to is the same as the runner that I am using. Also, my solution doesn't reference any projects that are outside the directory structure containing my .sln file.
Does anyone have any clue what I can do!? :(
Thanks!
Phil
NUnit version 2.5.10.11092
Copyright (C) 2002-2009 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.
Runtime Environment -
OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
CLR Version: 4.0.30319.1 ( Net 4.0 )
ProcessModel: Default DomainUsage: Default
Execution Runtime: net-4.0
Unhandled Exception:
System.IO.FileLoadException: Could not load file or assembly 'nunit.framework, Version=2.5.10.11092, Culture=neutral, Pu
blicKeyToken=96d09a1eb7f44a77' or one of its dependencies. The located assembly's manifest definition does not match the
assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'nunit.framework, Version=2.5.10.11092, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77'
Server stack trace:
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount,
IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInsta
ntiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHa
ndle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethod
Arguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope
, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilte
rType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMeth
odInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken,
Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecorate
dTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at NUnit.Core.CoreExtensions.InstallAdhocExtensions(Assembly assembly)
at NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
at NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
at NUnit.Core.SimpleTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.RemoteTestRunner.Load(TestPackage package)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server,
Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExec
uteInContext)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at NUnit.Core.TestRunner.Load(TestPackage package)
at NUnit.Util.TestDomain.Load(TestPackage package)
at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
at NUnit.ConsoleRunner.Runner.Main(String[] args)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Try using the Fusion Log Viewer to see what assembly is failing to load. It should tell you not only what file it is failing on, but where it tried looking for that file.
In my case nunit-console.exe did not respect the assembly redirection from web|app.config. unless you provide /domain=multiple
My Problem:
EntityFrameworkTesting.Moq -> requests Moq, Version=4.2.1409.1722
I had already a newer assembly referenced.
The solution for me was to add /domain=multiple parameter. see the NUnit docs
So I run:
D:\tools\NUnit-2.6.4\bin\nunit-console.exe %SOLUTION_PATH%\Project.sln /config:Release /framework:net-4.0 /domain=multiple /xml=nunit-result.xml