Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How To Connect MySQL With ASP.NET Core

$
0
0

I need connect .NET CORE Application with MySQL and read data from MySQL, using .NET Core MySQL connector

this is the tutorial

I followed step by step the instructions of the tutorial, but on debug in VS 2019 the error is

System.NullReferenceException:'Object reference not set to an instance of an object.'

ConnectionString is null, why?

On this part

privateMySqlConnectionGetConnection(){returnnewMySqlConnection(ConnectionString);}

Any idea?

I really tried everything I could find on google without success...

SakilaContext.cs

usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespace MvcSakilaCore.Models{publicclassSakilaContext{publicstringConnectionString{get;set;}publicSakilaContext(string connectionString){this.ConnectionString= connectionString;}privateMySqlConnectionGetConnection(){returnnewMySqlConnection(ConnectionString);}publicList<Film>GetAllFilms(){List<Film> list =newList<Film>();using(MySqlConnection conn =GetConnection()){
                conn.Open();MySqlCommand cmd =newMySqlCommand("SELECT * FROM film", conn);using(MySqlDataReader reader = cmd.ExecuteReader()){while(reader.Read()){
                        list.Add(newFilm(){FilmId= reader.GetInt32("film_id"),Title= reader.GetString("title"),Description= reader.GetString("description"),ReleaseYear= reader.GetInt32("release_year"),Length= reader.GetInt32("length"),Rating= reader.GetString("rating")});}}}return list;}}}

FilmsController

publicclassFilmsController:Controller{publicIActionResultIndex(){SakilaContext context =HttpContext.RequestServices.GetService(typeof(RazorPagesMovie.Models.SakilaContext))asSakilaContext;returnView(context.GetAllFilms());}}

Startup.cs

publicvoidConfigureServices(IServiceCollection services){
    services.AddControllersWithViews();
services.AddMvc();
services.AddTransient<MySqlConnection>(_ =>newMySqlConnection(Configuration["ConnectionStrings:DefaultConnection"])); services.Add(newServiceDescriptor(typeof(SakilaContext),newSakilaContext(Configuration.GetConnectionString("DefaultConnection"))));} app.UseEndpoints(endpoints =>{ endpoints.MapControllerRoute( name:"default", pattern:"{controller=Films}/{action=Index}/{id?}");});

appsettings.json

{"ConnectionsStrings":{"DefaultConnection":"server=localhost;port=3306;database=sakila;user=XXX;Password=XXX",
"ProviderName": "MySql.Data.MySqlClient"
},"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"}},"AllowedHosts":"*"}

Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>