how to connect mysql to .net program as 2nd db

I'm using mongodb in my program and I want to add second db and I decided to MySQL. I created the mysql container but don'tknow how to connect to program.
No description
No description
No description
93 Replies
Pobiega
Pobiega9mo ago
what do you mean by "second database"? what are you going to store in it? would you be running one or the other, or both at the same time?
only you know
only you knowOP9mo ago
I'll use both at the same time
Pobiega
Pobiega9mo ago
okay, then make a second DbContext oh right, its you again. you dont use EF for the mongo DB at all right? Repository over EF is considered a huge anti-pattern FYI
only you know
only you knowOP9mo ago
yeah but for mysql I didn't want to write all queries then what can I do except EF
Pobiega
Pobiega9mo ago
the trick isnt to replace EF its to not use a repository over EF just use the context directly
only you know
only you knowOP9mo ago
can I use mysql like i used mongodb?
Pobiega
Pobiega9mo ago
you can, using something like Dapper, or maybe even Linq2Db EF is however the "default" way to integrate with relational DBs in modern C#
only you know
only you knowOP9mo ago
but it's against my structure?
Pobiega
Pobiega9mo ago
then change your structure its really simple, just dont use a repository over EF in your service, inject the context itself, and use it directly keep the mongo repositories if you like, thats fine
only you know
only you knowOP9mo ago
you know I didn't want to use methods of mongo in my services directly
Pobiega
Pobiega9mo ago
yes so you introduced a repo to abstract mongo away but EF is that abstraction over mysql you could change mysql for postgres, and probably all you'd need to do was re-generate your migrations and DB Snapshot
Mih4n
Mih4n9mo ago
Em if u using ef coore and dependency injection u can just make another db context and then add it to injector
only you know
only you knowOP9mo ago
and also I can use EF for other dbs right? so make sense that i don't need a repo. so no need for making it generic its already
Mih4n
Mih4n9mo ago
Pretty easy
Pobiega
Pobiega9mo ago
yes, EF supports a whole range of relational DBs
Mih4n
Mih4n9mo ago
If u talking about postgresql and others there are a lot of extensions for them To connect ef core to them
Pobiega
Pobiega9mo ago
MSSQL (SQL Server), Postgres, MySQL, Sqlite, Cosmos, Oracle, even Mongo (but I dont recommend it)
Mih4n
Mih4n9mo ago
Mongo is non sql)
only you know
only you knowOP9mo ago
so for services that uses mongo I'll keep repos and for services that uses relational dbs no need for repos
Pobiega
Pobiega9mo ago
Im aware, thats why I dont recommend it.
only you know
only you knowOP9mo ago
yh im planning to use mysql
Pobiega
Pobiega9mo ago
specifically with EF Core, yes because EFCore itself already implements the repository pattern a Db Context contains one or more DbSet<T>s DbSet is a repository abstraction If you want shared, re-usable queries, like with a normal repository, you can implement that with extension methods on top of DbSet<T> for a given T
only you know
only you knowOP9mo ago
I'd like to cuz I don't want to define common crud methods over and over
Pobiega
Pobiega9mo ago
you dont EF already has all the CRUD _context.Posts.Add(new Post(...)); exists.
only you know
only you knowOP9mo ago
so I just define my custom methods
Pobiega
Pobiega9mo ago
same with Remove, Find(int id) etc yes, as extensions
only you know
only you knowOP9mo ago
got it but how do I connect it to mysql?
Pobiega
Pobiega9mo ago
// Replace 'YourDbContext' with the name of your own DbContext derived class.
services.AddDbContext<YourDbContext>(
dbContextOptions => dbContextOptions
.UseMySql(connectionString, serverVersion)
// The following three options help with debugging, but should
// be changed or removed for production.
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
);
// Replace 'YourDbContext' with the name of your own DbContext derived class.
services.AddDbContext<YourDbContext>(
dbContextOptions => dbContextOptions
.UseMySql(connectionString, serverVersion)
// The following three options help with debugging, but should
// be changed or removed for production.
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
);
make sure you use Pomelo.EntityFrameworkCore.MySql and not the other MySQL connector this one doesnt suck. the other one sucks.
only you know
only you knowOP9mo ago
which one is useless here
No description
only you know
only you knowOP9mo ago
also what am I missing is it about my dbcontext?
No description
only you know
only you knowOP9mo ago
No description
Pobiega
Pobiega9mo ago
The ones starting with MySql
only you know
only you knowOP9mo ago
what about my dbcontext?
Pobiega
Pobiega9mo ago
what about it? remove your OnConfiguring method, and change your constructor to inject the context options instead literally follow any sensible EF tutorial
public class TestAppContext : DbContext
{
public TestAppContext(DbContextOptions<TestAppContext> contextOptions) : base(contextOptions)
{
}
public class TestAppContext : DbContext
{
public TestAppContext(DbContextOptions<TestAppContext> contextOptions) : base(contextOptions)
{
}
thats how your ctor should look ofc you can rename the class itself, but you need that constructor argument
only you know
only you knowOP9mo ago
do i have to inject this to appcontext or I can use it from program.cs?
No description
Pobiega
Pobiega9mo ago
you would resolve that from program.cs and pass it into .UseMySql
only you know
only you knowOP9mo ago
how does it look
No description
Pobiega
Pobiega9mo ago
thats about right. just gotta fix your server version 😛
only you know
only you knowOP9mo ago
pls work🙏
No description
only you know
only you knowOP9mo ago
ups looks like I did all of this for nothing... my senior wants me to use sql without orm what path should I follow @Pobiega can you help me please?
Pobiega
Pobiega9mo ago
? Ask your senior, lol is Dapper fine? or does he explicitly want you to use ADO.NET? ask them, get an answer, use what they say or challenge the "no ERM" rule, but deal with them, not us
only you know
only you knowOP9mo ago
I asked him and he said "no orm at first write some sql query we'll see after"
leowest
leowest9mo ago
that means Ado dapper could also fit the bill but since its consider orm u can't the point of writing some sql is so you understand what it means to perform actions in the database
only you know
only you knowOP9mo ago
probably. I asked him is ado okay and he said it got many names 😄
leowest
leowest9mo ago
SELECT, UPDATE, INSERT, CREATE, using joins subqueries are all important aspects to understand before u go into ORMs sounds like a big yes to me
only you know
only you knowOP9mo ago
how do I connect to db while using ado mysql.client is okay?
Pobiega
Pobiega9mo ago
Be prepared for a lot of hard work when using ADO
leowest
leowest9mo ago
if not mistaken the counter part of ado for mysql is MySql.Data
Pobiega
Pobiega9mo ago
you need to manually map the results to the proper types, and line up your queries fields, order of select, etc yeah
leowest
leowest9mo ago
and the mysql docs are awful to follow @only you know https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials.html this one looks ok for a start
only you know
only you knowOP9mo ago
uhh looks scary
Pobiega
Pobiega9mo ago
guess why ORMs exist?
only you know
only you knowOP9mo ago
yh but rn not for me🥲 is it okay to construct crud methods in repo
Pobiega
Pobiega9mo ago
yes
only you know
only you knowOP9mo ago
public Follow GetFollowById(int id)
{
using(var conn = new SqlConnection(_connectionString))
using(var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, name FROM followedUsername WHERE id = @id";
cmd.Parameters.AddWithValue("id", id);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new Follow
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
FollowedUsername = reader.GetString(reader.GetOrdinal("username")),
};
}
}
}
public Follow GetFollowById(int id)
{
using(var conn = new SqlConnection(_connectionString))
using(var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, name FROM followedUsername WHERE id = @id";
cmd.Parameters.AddWithValue("id", id);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new Follow
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
FollowedUsername = reader.GetString(reader.GetOrdinal("username")),
};
}
}
}
how does it look
Pobiega
Pobiega9mo ago
SELECT id, name reader.GetOrdinal("username") one of these things is not like the other
only you know
only you knowOP9mo ago
fixed sorry except this any problem?
leowest
leowest9mo ago
I dont really like using getordinal I dont see much point in it and I imagine it might have a small overhead but aside from that looks like a start
only you know
only you knowOP9mo ago
thank you
only you know
only you knowOP9mo ago
how do I use my connection string? its in appsetting.json and I tried to register but couldn't do it.
No description
only you know
only you knowOP9mo ago
also here is the general look of my repo. does constructor look right
No description
only you know
only you knowOP9mo ago
oh I did like this
No description
only you know
only you knowOP9mo ago
@leowest @Pobiega when I register my IFollowRepo and Follow repo there is a problem because of IConfig how do I register it?
only you know
only you knowOP9mo ago
program.cs is like this atm
No description
only you know
only you knowOP9mo ago
No description
Pobiega
Pobiega9mo ago
you dont move it to its own config object IOptions<T>
only you know
only you knowOP9mo ago
@Pobiega am I connecting to mysql db wrong cuz when I run service there is error says that "System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. 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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'"
No description
No description
only you know
only you knowOP9mo ago
docker run --name mysql-demo -e MYSQL_ROOT_PASSWORD=ensar1234 -d -p 3307:3306 mysql
docker run --name mysql-demo -e MYSQL_ROOT_PASSWORD=ensar1234 -d -p 3307:3306 mysql
I created the container with this command
Pobiega
Pobiega9mo ago
uuhh yeah you are using new SqlConnection thats not for MySQL thats for SqlServer so you need to use their connection class
only you know
only you knowOP9mo ago
oh
Pobiega
Pobiega9mo ago
what connector did you install?
only you know
only you knowOP9mo ago
No description
Pobiega
Pobiega9mo ago
thats not for mysql >_>
only you know
only you knowOP9mo ago
🥺
Pobiega
Pobiega9mo ago
but also, why oh why are you using mysql its not a very good database to begin with
only you know
only you knowOP9mo ago
I have no idea just don't try to do as I'm told
only you know
only you knowOP9mo ago
how about this
No description
Pobiega
Pobiega9mo ago
yep that sounds good
only you know
only you knowOP9mo ago
I changed sql connection as mysqlconnection
No description
Pobiega
Pobiega9mo ago
yep thats a lot better
only you know
only you knowOP9mo ago
also I'm sure that mypw is true
Pobiega
Pobiega9mo ago
well, thats an actual response from your mysql server and it says that you did use a password, and you tried to connect as root and it failed. it almost has to be the password
only you know
only you knowOP9mo ago
if we look here we can't see the root user. does root default right so no need to be defined
Pobiega
Pobiega9mo ago
mhm can you connect to it with some client? HeidiSql, PhpMyAdmin etc?
only you know
only you knowOP9mo ago
I can connect from cmd and I created the db and table
Pobiega
Pobiega9mo ago
ok that should be enough set a breakpoint in your code, verify that its using the right password and that the encoding is correct
only you know
only you knowOP9mo ago
make sense let me try
Pobiega
Pobiega9mo ago
make sure your settingsfile is utf8
only you know
only you knowOP9mo ago
I can see that connection string comes as it should be
only you know
only you knowOP9mo ago
No description
Pobiega
Pobiega9mo ago
okay, dunno then
only you know
only you knowOP9mo ago
ohh thanks anyway
Want results from more Discord servers?
Add your server