Tag Archives: .net core

Unable to create object of type ‘ApplicationDbContext’ – Updating to .NET Core 3.0

Hi everyone,

I’ve just updated to .net core 3.0 and have been hitting a few issues. I hit this one while trying to add a migration:

Unable to create an object of type ‘ApplicationDbContext’. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Adding -verbose to this allowed me to narrow the cause down a little further:

PM> add-migration add-propertyid-to-entities-for-events -verbose
Using project ‘PropertyApi’.
Using startup project ‘PropertyApi’.
Build started…
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec –depsfile C:\Users\Celeste\Documents\repos\property-api\PropertyApi\bin\Debug\netcoreapp3.0\PropertyApi.deps.json –additionalprobingpath C:\Users\Celeste\.nuget\packages –additionalprobingpath “C:\Program Files\dotnet\sdk\NuGetFallbackFolder” –runtimeconfig C:\Users\Celeste\Documents\repos\property-api\PropertyApi\bin\Debug\netcoreapp3.0\PropertyApi.runtimeconfig.json C:\Users\Celeste\.nuget\packages\microsoft.entityframeworkcore.tools\3.0.0\tools\netcoreapp2.0\any\ef.dll migrations add add-propertyid-to-entities-for-events –json –verbose –no-color –prefix-output –assembly C:\Users\Celeste\Documents\repos\property-api\PropertyApi\bin\Debug\netcoreapp3.0\PropertyApi.dll –startup-assembly C:\Users\Celeste\Documents\repos\property-api\PropertyApi\bin\Debug\netcoreapp3.0\PropertyApi.dll –project-dir C:\Users\Celeste\Documents\repos\property-api\PropertyApi\ –language C# –working-dir C:\Users\Celeste\Documents\repos\property-api –root-namespace PropertyApi
Using assembly ‘PropertyApi’.
Using startup assembly ‘PropertyApi’.
Using application base ‘C:\Users\Celeste\Documents\repos\property-api\PropertyApi\bin\Debug\netcoreapp3.0’.
Using working directory ‘C:\Users\Celeste\Documents\repos\property-api\PropertyApi’.
Using root namespace ‘PropertyApi’.
Using project directory ‘C:\Users\Celeste\Documents\repos\property-api\PropertyApi\’.
Finding DbContext classes…
Finding IDesignTimeDbContextFactory implementations…
Finding application service provider…
Finding Microsoft.Extensions.Hosting service provider…
Using environment ‘Development’.
System.ArgumentNullException: Value cannot be null. (Parameter ‘implementationInstance’)

The key part here are the fact that it can’t find the config values and that it’s attempting to use the ‘Development’ env whereas it should be looking for ‘Local’.

It seems that during the upgrade all of my environment variables have been wiped. All that was required was to run the following (change local to match your environment):

$Env:ASPNETCORE_ENVIRONMENT = “Local”

Running the add-migration command should now user the local configuration. Thanks to the following link for the solution:
https://stackoverflow.com/a/50507486/522859

Advertisements

‘add-migration’ is not recognized as the name of a cmdlet – .net core 3.0

Hey everyone,

I recently upgraded my .net core 2.2 project to .net core 3.0. When trying to add a migration I hit the following error:

add-migration : The term ‘add-migration’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
+ add-migration events
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (add-migration:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

It turns out that there have been a few changes to how this all works. You’ll need to go to package manager console and run the following:

1) Install-Package Microsoft.EntityFrameworkCore.Tools
2) Update-Package Microsoft.EntityFrameworkCore.Tools
3) Get-Help about_EntityFrameworkCore

After running step three you should get something that looks like the following:

PM> Get-Help about_EntityFrameworkCore
ef-core

Covered in full here: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell

View Raw SQL in EF Core – Simple Option

Hi everyone,

I’ve been looking for a simple way of viewing the raw output of sql in my local environment without having to make code changes and came across the following config setup:

{
“Logging”: {
“LogLevel”: {
“Default”: “Debug”,
“System”: “Information”,
“Microsoft”: “Information”
}
}

This will show the sql statements in your output window without requiring any additional code:
sql-output

Thanks to this stackoverflow post for the answer: https://stackoverflow.com/a/54704006/522859

NetTopologySuite Circular Reference with .net core 2.2

Hey everyone,

Testing out a spatial project with .net core and I ran into the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : The best overloaded method match for ‘Xunit.Assert.Equal(string, string)’ has some invalid arguments

at CallSite.Target(Closure , CallSite , Type , Nullable`1 , Object )
at UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at DiscussionsControllerIntegrationTests.CreateTestDiscussion(HttpClient client, ApplicationDbContext db, DiscussionCreateWebRequest payload) in DiscussionsControllerIntegrationTests.cs line: 56
at DiscussionsControllerIntegrationTests.b__1_0(ApplicationDbContext db) in DiscussionsControllerIntegrationTests.cs line: 27
at IntegrationTestBase.RunTest(Func`2 testToExecute) in IntegrationTestBase.cs line: 54
at DiscussionsControllerIntegrationTests.CreateDiscussionIsSuccessful() in DiscussionsControllerIntegrationTests.cs line: 25
at — End of stack trace from previous location where exception was thrown —

Thankfully the solution is pretty straight forward. Install GeoJSON:

Install-Package NetTopologySuite.IO.GeoJSON

Then merge the following with your existing addMvc call in startup.cs:

services.AddMvc(options =>
            {
                // Prevent the following exception: 'This method does not support GeometryCollection arguments'
                // See: https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/585
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Point)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Coordinate)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(LineString)));
                options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MultiLineString)));
            })
                .AddJsonOptions(options =>
                {
                    foreach (var converter in NetTopologySuite.IO.GeoJsonSerializer.Create(new GeometryFactory(new PrecisionModel(), 4326)).Converters)
                    {
                        options.SerializerSettings.Converters.Add(converter);
                    }
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Unable to Migrate after Adding Config to Startup

Hi everyone,

Just a quick post on fixing up a migration error after I added new config to startup.cs via DI. The error after running add-migration was pretty unintuitive:

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

To find out a bit more I ran the following:

add-migration -verbose

This revealed the fact that there was an issue with adding my config line. The error stated that I had to have an empty constructor which led me on a bit of a wild goose chase.

The solution was simply a missed entry in application.json. In my case it was an omitted “assembly” section. Having said that, I did come across a few instances where people had the same problem when omitting commas etc.

Hopefully that’s able to get you on the right track!

Thanks,
Chris

.NET Core 2.1 is Returning JSON with Lowercase Properties

Hi everyone,

Just testing out .Net Core 2.1 and noticed that all of my JSON properties are being returned in lowercase despite being defined as uppercase. It turns out that this is configurable:


// Change from this
services.AddMvc();

// To this
services
        .AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Check out these links for more info:
https://stackoverflow.com/a/38202543/522859
https://github.com/aspnet/Announcements/issues/194