'C#, How to set up Database connection, and compare official documents with php laravel
I've writing php for a long time. Now I'm trying to use .net 6 mvc. But I don't know how to set up database connection and how to use it in a right way. I mean, not some test code of database connection in home controller, which I already did successfully.
using Microsoft.AspNetCore.Mvc;
using MVCTest.Models;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using MVCTest.Models;
namespace MVCTest.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View(GetAllUsers());
}
public IActionResult Privacy()
{
return View();
}
public IActionResult Register()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
private List<tUsers> GetAllUsers()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Server=localhost;database=MVCTEST;uid=sa;pwd=12345678";
con.Open();
//get adapter
String sql = "SELECT * FROM users";
SqlDataAdapter daUsers = new SqlDataAdapter(sql,con);
con.Close();
//fill adapter
DataSet ds = new DataSet();
daUsers.Fill(ds);
//get records
DataTable dtUsers = ds.Tables[0];
List<tUsers> users = new List<tUsers>();
foreach (DataRow row in dtUsers.Rows)
{
users.Add(new tUsers
{
code = row["code"].ToString(),
name = row["name"].ToString(),
});
}
return users;
}
}
}
This is what I copied from some post. But next?
I studied php and laravel all by my self. This page: https://laravel.com/docs/8.x/database Tells us there is a file .env, and the content:
...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
...
I know what to do at first sight. But .net6...
For local development, it gets the connection string from the appsettings.json file:
"ConnectionStrings": {
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-7dc5b790-765f-4381-988c-5167405bb107;Trusted_Connection=True;MultipleActiveResultSets=true"
}
How do I enter ip address, port, account and password ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
