DbContext class in .Net Core - asp.net-core

Hi Guys I am trying to migrate from Asp.Net MVC 5 to .Net Core 2.0 Web Application.
I am stuck with a error saying :
Cannot convert from 'string' to
'Microsoft.EntityFrameworkCore.DbContextOptions'
I get the above error when I hover over the class:
public class ExampleModelWrapper : DbContext
{
public ExampleModelWrapper()
: base("name=EXAMPLE_MODEL")
{
}
}
ExampleModelWrapper is a model.
I referred to the following question in stack overflow:
How can I implement DbContext Connection String in .NET Core?
I have the connection string in appsettings.json:
{
"ConnectionStrings": {
"EXAMPLE_MODEL": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Monitoring-CCA7D047-80AC-4E36-BAEA-3653D07D245A;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
I have provided the service in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
What can be the reason for the above error. I believe a connection is being established to the database successfully ,as it is working for the login and registration flow of Identity Db.I am also stumped on how or where to change the connections for the identity Db. Help appreciated , Thank you!!

You need to use the following constructor in your DbContext
public ExampleModelWrapper (DbContextOptions<ExampleModelWrapper> options)
: base(options)
{
}
Within your startup, you need to modify the following:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
to the following:
services.AddDbContext<ExampleModelWrapper>(options =>
options.UseSqlServer(Configuration.GetConnectionString("EXAMPLE_MODEL")));
Basically, you need to specify the DbContext you need to use.

Related

Not able to configure connection string in ASP.net MVC Core 5.0 & Entity Framework Core application

I'm getting below error when I configure SQL Connection in ASP.Net Core MVC 5 and Entity Framework core.
I've configured in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<VMSDBContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("VMSDatabase"))
);
}
My appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"VMSDatabase": "Server=.;Database=VMS;Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
You're looking for a connection called "VMSDatabase" in your code. But you've configured a connection called "AgileOneVMSDatabase" in your appsettings. Change either one of them so to the same and this should solve your issue.
According to your description, I guess the reason why you faced this issue is you used the wrong VMSDBContext's constructor method. If this class's
constructor method doesn't contains the DbContextOptions parameter, it will face this error.
I suggest you could change it like below:
public VMSDBContext(DbContextOptions options) : base(options) {}

Unable to resolve service for type 'Domain.IBlobModelCache' while attempting to activate 'Domain.EntityMaterializerSource'

Although the error message seems obvious I believe it is different from other questions. As you can see in my Startup I have registered IBlobModelCache service.
public class Startup
{
...
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<DataContext>(options =>
{
options
.ReplaceService<IEntityMaterializerSource, Domain.EntityMaterializerSource>();
.UseSqlServer(
Configuration.GetConnectionString("Default"),
opt => opt.MigrationsAssembly("API")
);
});
services
.AddAuthentication(ConfigureAthentication)
.AddJwtBearer(ConfigureJwtBearer);
services
.AddLogging(ConfigureLogging)
.AddTransient<IBlobPersisterFactory, BlobPersisterFactory>()
.AddTransient<IBlobDbContextSavingHandler, BlobDbContextSavingHandler>()
.AddTransient<IBlobDbContextModelCreator, BlobDbContextModelCreator>()
.AddSingleton<IBlobModelCache, BlobModelCache>() // It is here
.AddOptions<DiskBlobStorageSettings>().Configure<IConfiguration>((settings, config) => config.Bind("BlobStorage", settings));
}
...
}
And here the constructor of my services so you can see that there is not any loop in them.
class EntityMaterializerSource : Base.EntityMaterializerSource
{
public EntityMaterializerSource(
[NotNull] EntityMaterializerSourceDependencies dependencies,
IBlobModelCache blobModelCache
)
: base(dependencies)
{
BlobModelCache = blobModelCache;
OnMaterializedMethod = typeof(EntityMaterializerSource)
.GetMethod(nameof(OnMaterialized), BindingFlags.Instance | BindingFlags.NonPublic);
}
}
class BlobModelCache : IBlobModelCache
{
// Has no constructor
}
The BlobModelCache is resolved in other services successfully and the error only happens when EF needs to materialize entities.
All I need is to be notified when an entity is materialized from DB and I could not find any solution but extending EntityMaterializerSource. I am using EF Core 3.1.8 and ASP.Net Core 3.1.

Host a SignalR Hub in a .NET Core 3.1 Console

I migrating an old .NET library hosted by an exe from .NET Framework 4.6 to .NET Core 3.1. A part of the assembly is based on a stand alone SignalR hub implemented like this.
//-----------------------------------
// Startup SignalR Server
//-----------------------------------
m_oSignalRServer = WebApp.Start( C_AppSettings.ServerURL );
I understood that the host must be initiated with IHostBuilder and Host.CreateDefaultBuilder but I really don understand how to configure it. And especially, how to I specify the bindings and hub names.
Sample code or books are welcome.
learn.microsoft.com
public static IHostBuilder CreateHostBuilder( string [ ] args ) =>
Host.CreateDefaultBuilder( args ).ConfigureServices( ( hostContext, services ) =>
{
services.AddSignalR( ( hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes( 1 );
} ));
} );
Thanks in advance!
this is what I do and it works fine for me with a .net core 3.1 console app.
open up your .csproj and add the following to it:
<ItemGroup>
<FrameworkReference Include="Microsoft.aspNetCore.App" />
</ItemGroup>
then add the following package via nuget package manager:
Microsoft.AspNetCore.SignalR
this is my basic program.cs:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace GameServer
{
internal class Program
{
private static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
private static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}
}
and a basic Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace GameServer
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) { Configuration = configuration; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chat");
});
}
}
}
a lot simpler imo hope it helps :)
I trying to explain my problem in more details and hope someone know how to solve the issue.
Microsoft recommend to use Host.CreateDefaultBuilder instead of WebHost.CreateDefaultBuilder as I have understood. Host.CreateDefaultBuilder reads configuration from json files. The problem is that I don't understand how to connect the call services.AddSignalR() to my Hub.
In my old .NET 4.5 version it was easier from my point of view.
The server was started with this code
IDisposable oSignalRServer = WebApp.Start( "http://localhost:3211" );
And the hub was referenced with
ConnectionManager.GetHubContext<C_IOHub>()
Hub definition
[HubName( "IOHub" )]
public class C_IOHub : Hub
But with .NET Core I'm lost how to build this as a standalone server. All examples I have found describe how to attach the Hub to an existing MVC project.
I have a Startup.cs with the following code:
public static void Main( string [ ] args )
{
CreateHostBuilder( args ).Build().Run();
}
public static IHostBuilder CreateHostBuilder( string [ ] args ) =>
Host.CreateDefaultBuilder( args )
.ConfigureServices( ( hostContext, services ) =>
{
services.AddSignalR();
} );
I need the following information
How do I create a standalone Hub in .NET Core?
How do I obtain a reference to the Hub context?
Follows a full example to create and use a hub in the .NET Core 3.1 app:
First read the configuration from appsettings.json
"Azure": {
"SignalR": {
"ClientTimeoutInterval": 3600,
"HandshakeTimeout": 30,
"KeepAliveInterval": 15,
"EnableDetailedErrors": true,
"MaximumReceiveMessageSize": 32000,
"StreamBufferCapacity": 10,
"SupportedProtocols": [ "WebSockets", "ServerSentEvents" ],
"ServerConnectionCount": 1
}
}
Then read the configuration on the startup
private AzureConfiguration azureConfiguration;
Add in to configuration method
services.Configure<AzureConfiguration>(this.Configuration.GetSection(Azure)).AddOptionsSnapshot<Azure>();
Note: you can resolve the configuration like this this.azureConfiguration = provider.GetRequiredService<AzureConfiguration>();.
On the startup, configure method:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<YourHub>(this.azureConfiguration.SignalR.Endpoint)
});
On the configure services method:
services.AddSignalR(hubOptions =>
{
hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(this.azureConfiguration.SignalR.ClientTimeoutInterval);
hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(this.azureConfiguration.SignalR.HandshakeTimeout);
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(this.azureConfiguration.SignalR.KeepAliveInterval);
hubOptions.EnableDetailedErrors = this.azureConfiguration.SignalR.EnableDetailedErrors;
hubOptions.MaximumReceiveMessageSize = this.azureConfiguration.SignalR.MaximumReceiveMessageSize;
hubOptions.StreamBufferCapacity = this.azureConfiguration.SignalR.StreamBufferCapacity;
});
So your configuration on the startup is done, now just go create your hub.
After the hub is created, you can inject it using DI in to the controllers, workers, etc... like:
private IHubContext<YourHub, IYourHub> YourHub
{
get
{
return this.serviceProvider.GetRequiredService<IHubContext<YourHub, IYourHub>>();
}
}
PS: You should configure your CORS before adding the hub methods.
services.AddCors(options =>
{
options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});

Piranha cms with MySql

I'm trying to use pranha cms (5.3.1) with MySql. This is the code I'm using in my Startup.cs file, but I get this error:
InvalidOperationException: No service for type 'Piranha.IApi' has been registered. What may be the problem?
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
config.ModelBinderProviders.Insert(0, new Piranha.Manager.Binders.AbstractModelBinderProvider());
});
services.AddPiranhaApplication();
services.AddPiranhaFileStorage();
services.AddPiranhaImageSharp();
services.AddDbContext<Db>(options =>
options.UseMySql("server=localhost;port=3306;database=piranha-mysql;uid=root;password="));
services.AddPiranhaManager();
services.AddPiranhaMemCache();
return services.BuildServiceProvider();
}
Instead of calling AddDbContext you should use:
services.AddPiranhaEF(...);
Which both registers the DbContext and the API that should be used.
Regards

Setting Up ASP.NET Identity Core in an empty ASP.NET Core Web Application

I am trying to start a new web application project and I wanted to use the asp.net identity database (the one with all the AspNet tables (AspNetUsers, AspNetRoles etc)).
I have tried to follow numerous guides, these among other:
bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/
johnatten.com/2014/04/20/asp-net-mvc-and-identity-2-0-understanding-the-basics/
tektutorialshub.com/asp-net-identity-tutorial-basics/%20%22ASP.Net%20Identity%20Tutoria
benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
However when I tried to create the database I get this error.
I have also tried to do it by mimicking the template project (ASP.NET Core Web Application(.Net Core)) in Visual Studio with the same result or this one
This is how my project looks like, its basically the template minus the Controllers, Views and Models.
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//var connectionString = #"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Northwind;Integrated Security=True;Pooling=False";
//services.AddEntityFramework()
// .AddSqlServer()
// .AddDbContext<NorthwindContext>(o =>
// o.UseSqlServer(connString));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
I just want to have an empty project with asp.net identity, preferably in SQL server instead of in localdb. Does anyone have a easy guide or know why it does not work for me?
EDIT1
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : this("Data Source=ACLAP;Initial Catalog=tmpCore;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False") { }
}
EDIT2
I have put up the project on github.
github.com/KiBlob/test
Just an idea, do you have defined the DefaultConnection in your appsettings.json file?
Mine looks like this:
{
"ConnectionStrings": {
"DefaultConnection": "Server=[SERVER];Database=[DB];Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Try setting the connection there and then run Update-Database again.
Note: If you have multiple projects in your solution, make sure that the Default project in the package manager console is pointing to the project where the connection is set before running Update-Database.