I am currently trying to teach myself ASP.NET, as I will need it on the job soon. For testing purpose, I want to create a simple project with 1 or 2 RazorPages, which derives data from a MySQL database on my localhost. I am using the Visual Studio Community version. I started by creating a new ASP.NET Core Web Application project, then added a "New Connection" (see screenshot)
I also installed the packages "MySqlData", "MySqlData.EntityFrameworkCore" and "MySQLConnector". In appsettings.json, I added
"ConnectionStrings": {
"RazorPagesPlayersContext": "server=localhost;user=root;password=password;database=players;"
}
and in Startup.cs, I configured
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<RazorPagesPlayersContext>(options => options.UseSqlite(Configuration.GetConnectionString("RazorPagesPlayersContext")));
}
However, when I to go to the create page and post a new "player" into the database, I am getting error
ArgumentException: Connection string keyword 'server' is not supported
My context file looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using RazorPagesPlayers.Models;
namespace RazorPagesPlayers.Data
{
public class RazorPagesPlayersContext : DbContext
{
public RazorPagesPlayersContext (DbContextOptions<RazorPagesPlayersContext> options)
: base(options)
{
}
public DbSet<RazorPagesPlayers.Models.Player> Player { get; set; }
}
}
When I check "Connected Services", I can only see this
I can see, that the connection string of this service has nothing to do with the connection string I added in appsettings.json. When I try to change it, it will just switch back. So I am guessing the connection to MySQL failed or am I confusing things here? I am not even sure if I am looking in the right direction, but every hint would be most welcome. Thank you very much in advance
Edit: When I change the Service config in Startup.cs to
services.AddDbContext<RazorPagesPlayersContext>(options => options.UseMySql(Configuration.GetConnectionString("RazorPagesPlayersContext")));
it tells me "DbContextOptionsBuilder" does not contains a defintion for 'UseMySql' and recommends to change it to UseMySQL. This however results in an error:
TypeLoadException: Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory' from assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.
is there a point in installing Pomelo?
Related
I'm in the process of building a user management microservice using an API.NET Web API. I've added EntityFrameworkCore and using SQL Server as the database. I've made multiple services at this point, but this service does not seem to work the way I want it to.
FYI I'm using .NET 6.
The code you see below is how I add the AddDbContext to my Services in the Program.cs file.
builder.Services.AddDbContext<AppDbContext>(opt =>
{
// Getting the ConnectionString from the AppSettings-file.
string connectionString = builder.Configuration.GetConnectionString("Connection1");
Console.WriteLine("=====CONNECTION STRING=====");
Console.WriteLine("ConnectionString: " + connectionString + "\n");
Console.WriteLine("=====IT Asset Management=====");
Console.WriteLine("Service running: User Service");
if (builder.Environment.IsProduction())
Console.WriteLine("Environment is: PRODUCTION");
else
Console.WriteLine("Environment is: DEVELOPMENT");
// Configuring the DBContext to connect to the SQL server.
opt.UseSqlServer(connectionString);
});
When i run the code, my Console.WriteLines does not print, and it does not seem that the AddDbContext service gets initialized.
Below is my DbContext.
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using UserService.Models;
namespace UserService.Data
{
public class AppDbContext : IdentityDbContext<AppUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
}
}
As of now I have tried everything I can think of and gotten help from colleagues, but we can't seem to find out what's wrong. I have another service running the exact same code, but with a different purpose (Only the Program.cs files are the same), so I've tried to copy paste the file. I have tried to reinstall all the related NuGet-packages, which did not work.
Then i tried to create a new ASP.NET Web API project and only installing the packages needed to make the DbContext and setup the service in the Program.cs file. Below is the Program.cs file from the new project.
The funny thing is that it does not work aswell in the new project and I have no idea why.
using UserManagement.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(opt =>
{
Console.WriteLine("=====IT Asset Management=====");
Console.WriteLine("Service running: User Service");
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
I cannot think of anything I have done differently between these three projects.
UPDATE 1:
I found this post: AddDbContext doesn't call DbContext constructor
and one of the answers was that I needed to use migrations. I have not migrated anything from this project, since there is no tables to be made. I am using the default Identity tables, and they are created by another service. But when I added the migrations the Console.WriteLines got printed. Then i ran the project with "dotnet run" but then the prints were gone. Why is this?
So I seemed that one of the answers inside the post in UPDATE 1, actually was the solution to the issue. I did indeed have to use the DbContext in some context. I added a dataseeding class which is called from the program.cs file, and it seems that the console.writelines are printed every time now.
I have a database context that I am trying to update using DB scaffolding.
The command I am using in package manager console is:
Scaffold-DbContext Name="pwa_db" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data -Force
My appsettings.json looks like this:
"ConnectionStrings": {
"pwa_db": "Server=[My Server];Database=[My DB];Trusted_Connection=True;MultipleActiveResultSets=true"
}
yet when I run the command I get this error:
"A named connection string was used, but the name 'pwa_db' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information."
The strange thing is that this context was generated using this command so I'm not sure why it would stop working now.
I could easily get around this by just using the full connection string in the command instead of a named connection but then the DB context is generated with the connection string inside which I would prefer to avoid because you always get a warning like this:
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
The warning itself I'm not so concerned about because I'm using a trusted connection, so no credentials are being stored and I'm not expecting the source to ever leave our office.
Can anyone tell me what other configuration bits I might need to look at or what other issues may be at play? Because I can't see what is going wrong from the docs linked in any of the messages.
Have you tried adding the connection string to the appsettings.development.json file too?
I know this is old but maybe this can help someone else.
It works for me and I followed what you did in the scaffolding command and the json "ConnectionStrings". The error mentions IConfiguration. You are probably missing the connection set up in the Startup class.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<DTCCDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("pwa_db")));
...
}...
I have hosted Azure Function V3 on Azure Linux environment. I am trying to read the connection string from the configuration section. But I am not getting it. I tried to put the connection string on both, Application Settings as well as Connection Strings sections as shown below.
I am using dependency injection and my Startup class looks like below.
using BHD.Data.Data;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
[assembly: FunctionsStartup(typeof(BHD.AzureFunctions.Startup))]
namespace BHD.AzureFunctions
{
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var sqlConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
builder.Services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(sqlConnection));
}
}
}
I get NullPointerException on ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString even though the connection string exists in local.settings.json file as shown below.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
},
"ConnectionStrings": {
"DefaultConnection": "<My connection string>"
}
}
The way to get configuration in Azure Functions 2+ is IConfiguration, not ConfigurationManager.
You can inject IConfiguration into most places where you might inject anything else, but in Startup() you need to use something like this trick instead.
IConfiguration will automatically read from your function app settings when hosting in Azure, and your local.settings.json when run locally.
Edit (references):
The documentation for this is IMHO neither clear nor easy to find. There is also a lot of related discussion and confusion on GitHub.
The main source is DI in Azure Functions 2. Within it, most of what you need to know is almost easily missed:
The function host registers many services. The following services are safe to take as a dependency in your application:
[...] Microsoft.Extensions.Configuration.IConfiguration [...]
It also, in Working with options and settings says:
Values defined in app settings are available in an IConfiguration instance
The host does this for you; you do not need to do anything, and as above, it automatically gets settings from the correct source depending on your hosting context.
I've just started my first MVC 6 project in visual studio 2015.
I'm fairly new to MVC and have been working on various projects using web-forms in visual studio 2013 for the past year, but seeing as web forms is fairly outdated I decided to jump in with both feet into the newest version on MVC.
Every time I try to run the project or dnx ef database update I get the same error.
The server was not found or was not accessible. Verify that the
instance name is correct and that SQL Server is configured to allow
remote connections
I've created all my models with entity framework (code first) and set them to the context
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//UserModels
public DbSet<AppUser> Users { get; set; }
public DbSet<UserAddress> UserAddresses { get; set; }
//Other Models...
}
and set up my initial migration which all looks as it should.
I expected the database to be generated for me automatically in server explorer the first time I ran the application but I've seen that this is not something that's set up by default in MVC 6.
I've been following various tutorials and currently have in my appsettings.json
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=TestDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
and startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
I assume the problem is something to do with with either the way my connection string is formatted or being passed into ConfigureServices as my localDb is set to allow remote connections.
Sorry for the long winded question, but I've been banging my head off the wall for most of the day!
I have an MVC4 website and I am trying to integrate some Mongodb functionality (just experimenting for now). I am using this mongodb project as I am also trying to deploy to Azure, this project provides connection utilities for connecting to the mongodb worker role. I have a MovieController with the following constructor:
public class MovieController : Controller
{
MongoMovieHelper _movies;
public MovieController()
{
_movies = new MongoMovieHelper();
}
}
This in turn calls the class:
public class MongoMovieHelper
{
public MongoCollection<Movie> Collection { get; private set; }
public MongoMovieHelper()
{
MongoServerSettings serverSettings = ConnectionUtilities.GetConnectionSettings();
MongoServer server = MongoServer.Create(serverSettings);
MongoDatabase db = server["movies"];
Collection = db.GetCollection<Movie>(typeof(Movie).Name.ToLower());
}
...
When trying to load any page from the Movie controller I get an internal server error in the Chrome debugger.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
So I tried debugging in visual studio. The controller constructor gets hit, but any breakpoints within MongoMovieHelper do not, and trying to Step into just hits the controller constructor again. The stack trace displays the following error:
Could not load file or assembly 'MongoDB.Driver, Version=1.4.2.4500,
Culture=neutral, PublicKeyToken=f686731cfb9cc103' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
Previously I had another class which makes the Mongodb connection so Controller calls MongoMovieHelper which calls MongoDBHelper. In this case, both the controller and MongoMovieHelper were being called, but MongoDBHelper was not, so I believe the problem lies within the mongodb connection.
This is probably some rookie mistake but I just can't figure out what the problem might be, any ideas?
I tried to recreate your problem using the latest version of the official mongodb c# driver but I could not.
I am using the latest official driver available on NuGet:
I changed your code to use non-obsolete methods to get the server object:
public MongoMovieHelper()
{
var client = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
var server = client.GetServer();
var db = server["movies"];
Collection = db.GetCollection<Movie>(typeof (Movie).Name.ToLower());
}
So if you are not using the official driver then please use it:
get using the following command:
Install-Package mongocsharpdriver
Then try and change your code to look something like mine and then see if it works.
The error you are getting suggests you are either using an old version of the official driver, or you aren't using the official driver at all.
Note: uninstall the old driver, either through the nuget console (/ui), alternatively remove the binary ref and clean your project ensuring that you don't have any bin dll left hanging around.