add migration failed when DbContext in sperate project - c#

I have a project with different layers: web, services, model, data each one has a different project in the same solution. The application, compiles and runs OK. But when I tried to implement migration I got the following error
dnx . ef migration add MigrationFile
System.InvalidOperationException: No DbContext was found. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
at Microsoft.Data.Entity.Commands.ContextTool.SelectType(IEnumerable`1 types, String name)
at Microsoft.Data.Entity.Commands.MigrationTool.GetContextType(String name)
at Microsoft.Data.Entity.Commands.MigrationTool.AddMigration(String migrationName, String contextTypeName, String startupAssemblyName, String rootNamespace,String projectDir)
at Microsoft.Data.Entity.Commands.Program.<>c__DisplayClass12_0.<AddMigration>b__0()
at Microsoft.Data.Entity.Commands.Program.Execute(String startupProject, Func`1 invoke)
at Microsoft.Framework.Runtime.Common.CommandLine.CommandLineApplication.Execute(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host,String applicationName, String[] args)
at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.Execute(String[] args, FrameworkName targetFramework)

I'm using this answer as a reference.
Maybe your project has more than one DbContext or you have not turned on the migrations.
If you have more than one Context, you will want to enable and add migrations for each Context separately:
add-migration -ConfigurationTypeName MyProject.MigrationsFolder.Configuration "migrationName"
This code will add a new Migration based on your Context and using the Configuration class associated to it. The following code will update the database associated with the Configuration class.
update-database -ConfigurationTypeName MyProject.MigrationsFolder.Configuration

the commands must be like this
- dnu restore
cd the project which contain the context path
dnx . ef migration add -c ContextName - s StartupProjectName
try it and if this work let me know, thnx ^^

Related

IOptions configurations throws random NullReferenceException - AspNetCore 2.2

I have an WebApi app targeting net framework 4.6.1 and using AspNetCore 2.2 :
Setup:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<EmailConfig>(Configuration.GetSection("EmailConfig"));
services.AddTransient<IEmailService, EmailService>();
}
Injecting:
public EmailService(IOptions<EmailConfig> emailConfig)
{
_emailConfig = emailConfig.Value;
}
The setup works fine at the first look, but under some load testing I have noticed that I get the following error when the DI container tries to get the IOptions<EmailConfig>:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Extensions.Configuration.ConfigurationProvider.<>c__DisplayClass9_0.<GetChildKeys>b__0(KeyValuePair`2 kv)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__59`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__59`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__59`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at Microsoft.Extensions.Configuration.ChainedConfigurationProvider.GetChildKeys(IEnumerable`1 earlierKeys, String parentPath)
at System.Linq.Enumerable.Aggregate[TSource,TAccumulate](IEnumerable`1 source, TAccumulate seed, Func`3 func)
at Microsoft.Extensions.Configuration.ConfigurationRoot.GetChildrenImplementation(String path)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration configuration, Object instance, Action`1 configureOptions)
at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at System.Lazy`1.CreateValue()
Does anyone got trough this type of problem?
Later Edit:
Removing the IOptions<EmailConfig> from the EmailService and injecting the IConfiguration directly and then getting my emailConfigs from IConfiguration manually, works great and solves my problem.
But still, in order to respect the ISP and SoC principles when using configurations, the recommended way to do it by the aspnetcore team is using Options Pattern, but looks like it is not working fine all the time.
I am starting to think that maybe there is a problem with my setup: aspnetcore 2.2 targeting netFramework 4.6.1. I'll try to upgrade to the latest netcore and also change the target to netcore to see if the problem reproduces.

ReflectionTypeLoadException exception in Asp.Net Core in-memory TestServer

I create a IWebHostBuilder like so:
public IWebHostBuilder GetWebHostBuilder()
{
return new WebHostBuilder().UseContentRoot(_contentRoot)
.ConfigureServices(InitializeServiceCollection)
.UseEnvironment(_environment)
.UseConfiguration(GetConfiguration())
.UseStartup(typeof(TStartup));
}
Here, the InitializeServiceCollection is implemented like so:
private void InitializeServiceCollection(IServiceCollection services)
{
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(_assembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
services.AddSingleton(manager);
}
Then I create the TestServer like so:
var myTestServer = new TestServer(GetWebHostBuilder());
Here I get the exception (full exception below). It gets thrown at services.AddAutoMapper(); method call in the system under test. However, when I run the system under test on it's own and test it manually with Postman, it's working fine and the object mapping with Automapper is working well too. It just raises the exception in the integration test.
Full exception:
System.AggregateException : One or more errors occurred. (Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.) (The following constructor parameters did not have matching fixture data: TestFixture fixture)
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
---- The following constructor parameters did not have matching fixture data: TestFixture fixture
----- Inner Stack Trace #1 (System.Reflection.ReflectionTypeLoadException) -----
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeAssembly.get_DefinedTypes()
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`2 configAction, IEnumerable`1 assembliesToScan) in xxx\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensions.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 72
at xxx.Startup.ConfigureServices(IServiceCollection services) in xxx\Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
at xxx.Tests.TestFixture.InitializeServer() in xxx.Tests\TestFixture.cs:line 67
at xxx.Tests.TestFixture..ctor() in xxx.Tests\TestFixture.cs:line 31
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----
So, I managed to resolve the issue by replacing services.AddAutoMapper() with services.AddAutoMapper(Type[] types) overload. Not sure what is wrong with the original method, but in order to avoid that reflective call on the assemblies, I used this overload and it's working now.

Unable to resolve dependency when running dotnet core app from console

I am writing a client-server application using Dotnet Core web-api as the backend and Angular2 for the frontend. The persistence layer uses EntityFramework Core to access a postgre database. To try my application I added a database seeding class to create some test data to work with. With this class my problem started.
When I run the application from Visual Studio Code everything is working fine. If I start the application from the terminal with "dotnet run" I get the following exception:
Unhandled Exception: System.Exception: Could not resolve a service of type 'OpenGameListApp.Data.DbSeeder' for the parameter 'dbSeeder' of method 'Configure' on type 'OpenGameListApp.Startup'. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.NpgsqlDbContextOptionsExtensions.UseNpgsql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 NpgsqlOptionsAction)
at OpenGameListApp.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in /home/noam/projects/dotnet/OpenGameListApp/src/Startup.cs:line 43
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at OpenGameListApp.Program.Main(String[] args) in /home/noam/projects/dotnet/OpenGameListApp/src/Program.cs:line 15
The code of the Startup.cs class:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc();
// Add entity framework
services.AddEntityFrameworkNpgsql()
.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add database seeder
services.AddSingleton<DbSeeder>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
{
// Add logger
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Rewrite all routing urls including the root one to the index.html file by adding the following rules
var rewriteOptions = new RewriteOptions().AddIISUrlRewrite(env.ContentRootFileProvider, "rewrite-rules.xml");
// Add iis url rewrite features to kestrel
// Note: the app.UseRewriter method must be called before app.UseDefaultFiles and app.UseStaticFiles
app.UseRewriter(rewriteOptions);
// In order for your Web app to serve a default page without the user having to fully qualify the URI,
app.UseDefaultFiles();
// Enable service of static files in wwwroot folder
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching for all static files
context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
context.Context.Response.Headers["Pragma"] = Configuration["StaticFiles:Headers:Pragma"];
context.Context.Response.Headers["Expires"] = Configuration["StaticFiles:Headers:Expires"];
}
});
// Enable the use of asp.net mvc framework
app.UseMvc();
// Initialize auto mapper
Mapper.Initialize(cfg => cfg.CreateMap<Item, ItemViewModel>());
// Seed database
dbSeeder.SeedIt();
}
The exception goes away if I remove the dbSeeder from the Startup class. I would really appreciate if someone could point out to me what is happening here.
The comment of Martin Ullrich pointed me in the right direction:
it looks like the connection string cannot be read from the configuration since the call to UseNpgsql() throws
The connection string could indeed not be read from the configuration. In my project I have two different appsettings files: appsettings.development.json and appsettings.json. Only the former contains the connection string. When I run the application in Visual Studio Code it starts in debug environment and is therefore able to read the connection string.
Running the application from the terminal with dotnet run however seems to run the application in production environment. After changing the environment used in the terminal to development (export ASPNETCORE_ENVIRONMENT=Development) everything works fine.

Entity Framework 7 no database provider is configured => when migrations are moved to another project

I am new to EF7. I know this is a duplicate question to:
No database providers are configured EF7
But wait before you want to have this question closed... and read on
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddScoped<TestRepository, TestRepository>();
Now I run the dnx ef database update command on the cmd windows in my EF project and get this error:
C:\TGB.DataAccess>dnx ef database update
System.InvalidOperationException: No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
bei Microsoft.Data.Entity.Internal.DatabaseProviderSelector.SelectServices(ServiceProviderSource providerSource)
bei Microsoft.Data.Entity.Internal.DbContextServices.<>c__DisplayClass6_0.<Initialize>b__0()
bei Microsoft.Data.Entity.Internal.LazyRef`1.get_Value()
bei Microsoft.Data.Entity.Internal.DbContextServices.get_DatabaseProviderServices()
bei Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_8(IServiceProvider p)
bei Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
bei Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
bei Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
bei Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
bei Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
bei Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
bei Microsoft.Data.Entity.Design.Internal.DesignTimeServicesBuilder.Build(DbContext context)
bei Microsoft.Data.Entity.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
bei Microsoft.Data.Entity.Commands.Program.Executor.<>c__DisplayClass7_0.<UpdateDatabase>b__0()
bei Microsoft.Data.Entity.Commands.Program.Executor.Execute(Action action)
No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
Now I tried to change the constructor of my ApplicationDbContext according to the solution link I pasted at the top:
Thats my code:
My ApplicationDbContext.cs is actually empty that means nothing I have overridden.
Looking at the base class of the base class there is the overloaded constructor with parameter DbContextOptions but I can not pass anything from my constructor?!
//
// Summary:
// Initializes a new instance of Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext.
//
// Parameters:
// options:
// The options to be used by a Microsoft.Data.Entity.DbContext.
public IdentityDbContext(DbContextOptions options);
What is broken on my side? I am using EF 7 RC1 and dnx 451.
This happens only when you move the ApplicationDbContext/ApplicationUser and the whole Migrations folder to an extra lets say "DataAccess" project. Then everything seems broken.
Create a new ASP.NET Web Application named "WebProject" using Web Application template (Authentication: Individual User Account).
Now add another project to the solution named "DataAccess" (let's say Class Library type though its not relevant)
Now move ApplicationDbContext/ApplicationUser files & migrations folder to DataAccess project.
At this stage the build will be failing, so we need to correct the project.json for correct references.
For DataAccess project, add following dependencies
"dependencies": {
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"
}
For WebProject, add DataAccess as dependency. Since DataAccess has reference to above 2 packages, you can remove those references from WebProject.
Build should succeed now and you can launch web application.
How to use ef migrations:
In command line, go to directory of WebProject (and not the DataAccess project).
All the ef commands will work fine from here.
To add new migrations to the Migrations folder of DataAccess project, you need to use -p flag. Like,
dnx ef migrations add Sample -p DataAccess.
The issue arises because the commands are run from cmd within DataAccess project. Your startup class which is initializing all the services is in WebProject. When you try to run commands from DataAccess directory, dnx ef will be recognized since EntityFramework.Commands is referenced but when you try to use the migrations, services are not initialized therefore it will fail throwing above exception.
Try to move your Context class to your "DataAccess" project and override the OnConfiguring method of your Context in your "DataAccess" project then run the migration.
public partial class MyContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(#"Server=****;Database=***;user id=***;password=***");
}
}
Or you can do like followings if you don't want to hard code your connection string. DI will inject the options for you;
public partial class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
}
and on your Startup.cs;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<WtContext>(options =>
options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"]));
}
and your appsetting.json;
{
"Data": {
"MyDb": {
"ConnectionString": "**********"
}
}
}

Exceptions for Entity Framework Code First Migrations

I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.
The database context:
public class MyAppContext : DbContext
{
public DbSet<Branch> Branches { get; set; }
public MyAppContext()
{ }
}
The entity:
public class Branch : IEntity<Guid>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
}
The database initializer:
public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
context.SaveChanges();
}
}
I installed Entity Framework 4.3 to my DAL project and MVC project using:
Install-Package EntityFramework
I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:
PM> Enable-Migrations -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'.
Error while searching for context type (specify -Verbose to see exception details).
System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. at
System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner) at
System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()
at
System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable()
Edit the generated Configuration class to specify the context to
enable migrations for.
Code First Migrations enabled for project Ckms.KeyManagement.Managers.
A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:
internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyAppContext context)
{ }
}
These exceptions are thrown for the Add-Migration and Update-Database commands:
PM> Add-Migration TestEFMigrationsColumn -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. 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.
Update-Database:
PM> Update-Database -Verbose
Using NuGet project
'Ckms.KeyManagement.Managers'. 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.
Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.
If you are using separate library for data access you need to provide it name when running query:
Add-Migration -StartUpProjectName "Your DAL Project" MyNewMigration
Update-Database -StartUpProjectName "Your DAL Project" -Verbose
add-migration -Name First -ProjectName DbSet.Framework -StartUpProjectName CodeFirstConsole
First: Name of Migration
Dbset.Framework: Project where dbContext and other classes
CodeFirstConsole: Start Up project (could be your web, windows or console app)
For System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) adding -projectname and startupprojectname did not help.
Setting the PackageManager Console's "Default Project" Dropdown to point to the Library (in my case) where I wanted the "Migration folder" and its expected contents to be was the only way to get this running from a multiproject solution.
I also had the same issue. Found out that if anything is wrong with the config files this error comes up. I had duplicate tags in web.config and removing these solved my issue.
I had solve this problem only by changing the name used in connection string.
<add name="abcd" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
And I use connectionStrings after closing tag of the
appSettings
and just before starting tag of
system.web
Make sure that name that you use in connectionString not used in other connections.
Ran into the same problem , solved by removing <globalization> from web.config.
You must be having two connection strings in your web. Config files. Just delete one

Categories