blob: b07aa5a7495cede9632d7fe3e8d4a5f5b5dd5f0b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
# Connect to MySql in C# and Entity Framework - Connecting
**Article Created: 21 May 2020** || **Last Edited: 21 July 2020**
[\<\<](./introduction.html) || [\< Preparations](./preparation.html)
---
## Connection string
You can find many ways to impliment your connection string from [here](https://www.connectionstrings.com/mysql/).
From experience, this one works the best:
```
"server=localhost; port=YOUR-PORT; user id=YOUR-USER-ID; password=YOUR-PASSWORD; database=NAME-OF-DATABASE; SslMode=none"
```
If you don't know your port or user id, just look at the connection you use to connect to the database.
 In this example, the user id is _root_ and the port is _3306_.
## ASP.NET Startup
If you are making an ASP.NET application, you will need to alter your Startup.cs file.
Your ConfigureServices method should currenly look something like this:
```
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<UserServices, UserServices>();
services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSQL(CONNECTION_STRING);
});
}
```
You need to change `.UseSQL` to `.UseMySQL` (refer to [preparations](./preparation.html) if you haven't already).
## DBContext child class
If you want to connect a DBContext child class to a MySQL databse, the best way is to override the `OnConfiguring` method. In the override, in `optionsBuilder`, call the `.UseMySQL` method (refer to [preparations](./preparation.html) if you haven't already).
Example:
```
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL(DataBaseContexts.ConnectionStringMySQL);
}
```
Now you should be connected to your database.
|