I've just started to migrate to a SQL database and running into a problem with a MissingMethodException being thrown. Here is the configuration class that is throwing the error:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Project.Core.Entities.Users;
namespace Project.Persistance.Configuration.Users
{
public class UserClaimTypeConfiguration : IEntityTypeConfiguration<UserClaimType>
{
public void Configure(EntityTypeBuilder<UserClaimType> builder)
{
builder.HasKey(entity => entity.Id);
builder.Property(entity => entity.Name)
.IsRequired()
.HasMaxLength(30);
builder.HasIndex(entity => entity.Name);
builder.Property(entity => entity.Description)
.IsRequired(false)
.HasMaxLength(100);
builder.Ignore(entity => entity.ValueType);
}
}
}
And this is error I am getting in the console:
PM> add-migration user
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Builders.IndexBuilder Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasIndex(System.Linq.Expressions.Expression`1<System.Func`2<!0,System.Object>>)'.
at Project.Persistance.Configuration.Users.UserClaimTypeConfiguration.Configure(EntityTypeBuilder`1 builder)
at Microsoft.EntityFrameworkCore.ModelBuilder.ApplyConfiguration[TEntity](IEntityTypeConfiguration`1 configuration)
I've tried 'Goggle' and the Microsoft docs but can't seem to find any reference to this issue - so it must be my setup. Just can't figure out what is causing it!
Breaking change in .NET Core 3.0 preview 3. Fixed in preview 4:
ASP.NET Core Issue 8467 (RESOLVED)
Based on this document:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.builders.entitytypebuilder-1.hasindex?view=efcore-3.1
Implementation of this method is done in Microsoft.EntityFrameworkCore versions 3.1 3.0 2.2 2.1 2.0 1.1 1.0
You have to check your Microsoft.EntityFrameworkCore version. It should be one of the above versions. If it does not work for a versoin try another.
Related
I have an ASP.NET Web API application running on .NET 4.8. In this app, I'm using standard Microsoft API versioning from Microsoft.AspNet.WebApi.Versioning and Microsoft.AspNet.WebApi.Versioning.ApiExplorer.
For instance:
[ApiVersionExtended(SupportedApiVersions.V9)]
[RoutePrefix("v{version:apiVersion}/telemetry")]
public sealed class TelemetryController : ApiController
{
where ApiVersionExtended - my filter. In Azure Application Insight requests to my API are shown with the correct version. For instance:
But after migration to .NET 6, I lost the correct version number in AI logs, for instance:
My code has several changes after migration to .NET 6
[ApiController]
[AllowAnonymous]
[ApiVersionExtended]
[Route("v{version:apiVersion}/telemetry")]
public sealed class TelemetryController : ApiController
{
[HttpGet("ipInfo")]
public async Task<IActionResult> GetIpInfoAsync(CancellationToken cancellationToken)
{
/* some code here */
}
}
I can't find the analog [RoutePrefix] attribute in .NET 6.
Might someone know what the reason for this issue is? And how I can fix it?
As suggested by #Peter Bons, this can be the issue with your existing Nuget Package.
The Nuget Package required to Implement API Versioning in .NET 6 Core Web API is Microsoft.AspNetCore.Mvc.Versioning
Install Microsoft.AspNetCore.Mvc.Versioning Nuget Package
In Program.cs add the below services
To add versioning for WebAPI
builder.Services.AddApiVersioning(opt =>
{
opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(2, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
opt.ReportApiVersions = true;
opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("x-api-version"),
new MediaTypeApiVersionReader("x-api-version"));
});
To Add versioning with Swagger, add the below services
builder.Services.AddSwaggerGen(Options => Options.SwaggerDoc("v1", new OpenApiInfo { Title = "Audit Self Serve platform", Version = "v1" }));
Use MapToApiVersion attribute to assign each action to a distinct version
[MapToApiVersion("1.0")]
[HttpGet]
OutPut:
I'm working on a simple .NET 6 application to enable data update notifications in our front-end application. I've built something similar in .NET 5 before, but I'm running across a DI issue that's got me stumped. In 5, all hubs that were mapped automatically have an IHubContext that is set up in the container for them as well. That doesn't appear to be the case anymore in 6.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]' while attempting to activate 'SignalRNotifications.Controllers.NotificationController'.
The new non-startup DI in 6 looks weird to me, but I'm just not seeing anything available that says how to fix it. Any suggestions on how to get an IHubContext to inject into my controller?
Thanks!
Update: Here is some pertinent code:
using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/NotificationHub");
});
app.Run();
Dependency injection is done in the controller in the most predictable of ways:
namespace SignalRNotifications.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly IHubContext<NotificationHub> _notificationContext;
public NotificationController(IHubContext<NotificationHub> notificationContext)
{
_notificationContext = notificationContext;
}
System.InvalidOperationException: Unable to resolve service for type
'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]'
while attempting to activate
'SignalRNotifications.Controllers.NotificationController'.
The issue might be related to you having installed the wrong version of SignalR and adding the wrong namespace reference. You are using Microsoft.AspNet.SignalR.IHubContext, instead of Microsoft.AspNetCore.SignalR.IHubContext.
According to your code and refer to the Asp.net Core SignalR document, I create a sample and inject an instance of IHubContext in a controller, everything works well. But I notice that when using the IHubContext, we need to add the using Microsoft.AspNetCore.SignalR; namespace, like this:
So, please check your code and try to use:
using Microsoft.AspNetCore.SignalR;
I have converted my .net core 2.2 to .net core 3.1. I am getting issue with following below.
Getting complain about MvcJsonOptions inside IOptions<MvcJsonOptions> options.
Also getting issue with MvcOptions inside IOptions<MvcOptions>.
Another one is, options.SerializerSettings inside SetupSerialiserSettings(options.SerializerSettings).
public JsonDeserialiser(IOptions<MvcJsonOptions> options) : this(options.Value.SerializerSettings)
{
}
services.AddSingleton<IObjectModelValidator>(
s =>
{
var options = s.GetRequiredService<IOptions<MvcOptions>>().Value;
});
services.AddControllers()
.AddJsonOptions(options => SetupSerialiserSettings(options.SerializerSettings))
Firstly,you can refer to the link and find MvcJsonOptions only applies to 2.1, 1.0, 1.1, 2.0, 2.2.And you can also refer to Breaking changes to Microsoft.AspNetCore.App in 3.0.
In .net core 3.1,the internal usage of Json.NET in ASP.NET Core has be replaced by the new platform-provided JSON APIs.Refer to The future of JSON in .NET Core 3.0.
So you can try to add package Microsoft.AspNetCore.Mvc.NewtonsoftJson,and use like the following code(from the official doc):
services.AddControllers().AddNewtonsoftJson(options =>
{
...
});
I am trying to debug an issue in an asp.net core 3.1 REST API. This application has been upgraded to asp.net core 3.1 from 2.2. The asp.net core 3.1 version includes the package Microsoft.AspNetCore.Mvc.NewtonsoftJson as it doesn't come by default. Otherwise, I don't see much difference.
The problem is that one of the endpoints shown below is working fine in 2.2 but throws an exception in 3.1.
public async Task<ActionResult<MyResponse>> ActionMethod1([FromBody] ChildClass request){
MyResponse response = new MyResponse();//Line 2
//Some code
}
ChildClass:Parent1{
public C_property1{get;set;}
public C_property2{get;set;}
public C_property3{get;set;}
}
Parent1:Parent2{
public p1_property1{get;set;}
public p1_property2{
get{ return SomeClass.Somemethod(p1_property1)//Somemethod throws an exception
}
}
}
When I debugged the issue, I noticed that the 2.2 version doesn't try to initialize the properties of Parent1. But the 3.1 version code tries to initialize the parent1 properties. This makes SomeClass.Somemethod() to be called which throws an exception. On the controller, the breakpoint doesn't even get to Line 2. It is not clear why this version behaves differently.
I thought it could be because of JSON.net deserializer settings. I tried adding the below on all the properties of parent1, it didn't work. Please suggest what could have changed here.
[JsonIgnore] [JsonProperty(Required = Required.Default)]
I have a ASP.NET 5 project in VS 2015 (Beta 8) that includes EF 7 which is working on Full-CLR but not Core-CLR. Below is the partial configuration:
"dependencies": {
"EntityFramework.Commands": "7.0.0-beta8",
"EntityFramework.SQLite": "7.0.0-beta8",
"EntityFramework.SQLite.Design": "7.0.0-beta8"
}
services.AddEntityFramework()
.AddSqlite();
When using the above and publishing to Docker I get the following error:
DNX,Version=v4.5.1 error CS1061: 'EntityFrameworkServicesBuilder' does
not contain a definition for 'AddSqlite' and no extension method
'AddSqlite' accepting a first argument of type
'EntityFrameworkServicesBuilder' could be found.
If I remove the EntityFramework.SQLite.Design dependency it then works. I understand that EF 7 is still in beta and that the SQLite provider is incomplete, but is there a workaround? I don't plan to use migrations in Linux.
UPDATE
I was thinking that I could create an extension method to ensure a successful compilation, but this class wasn't recognized.
#if DNXCORE50
public static class SqliteEntityServicesBuilderExtensions
{
public static EntityFrameworkServicesBuilder AddSqlite(
this EntityFrameworkServicesBuilder services)
{
throw new NotImplementedException();
}
}
#endif
Microsoft found a bug concerning case-sensitive package names.
Changing the dependency from EntityFramework.SQLite.Design to EntityFramework.Sqlite.Design resolved the issue.