dotNet 6.0 프로젝트에서 EntityFramework를 사용해 MariaDB에 연결하는 방법에 대해 알아봅니다.
1. NuGet 패키지 설치.
다음 NuGet 패키지를 설치합니다.
2. DB 테이블 생성
DB에 접속해 다음 예시와 같이 테이블을 생성합니다.
CREATE TABLE `dev_db`.`users` (
`Key` INT NOT NULL AUTO_INCREMENT,
`Id` VARCHAR(128) NOT NULL,
`Name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`Key`),
UNIQUE INDEX `Key_UNIQUE` (`Key` ASC) VISIBLE,
UNIQUE INDEX `Id_UNIQUE` (`Id` ASC) VISIBLE);
3. DBContext 생성
다음 예시와 같이 Model과 DbContext를 생성합니다.
//Model: User
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public User(string id, string name)
{
this.Id = id;
this.Name = name;
}
}
//DbContext: UserContext
public class UserContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var connectionString = "server=localhost; database=dev_db; user=dev; password=devpass";
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
}
}
4. User 추가
다음 예시 코드를 실행해 Users 테이블에 User를 추가합니다.
// Insert a new user to users table.
using (var context = new UserContext())
{
context.Users.Add(new User("testID", "testName"));
context.SaveChanges();
}
DB에 정상적으로 데이터가 추가된 것을 확인할 수 있습니다.
반응형
'Programming > C#' 카테고리의 다른 글
[MongoDB] MongoDB Driver Upgrade 1.x ⇒ 2.x (0) | 2022.09.05 |
---|---|
[C#] Entity Framework를 사용해 join 쿼리문을 수행하는 방법. (0) | 2022.07.26 |
[C#] 액세스 한정자: Access Modifiers (0) | 2022.05.03 |
Cannot load Counter Name data because an invalid index '' was read from the registry. (0) | 2022.05.02 |
[C#] Hostname으로 IP 주소 가져오기. (0) | 2021.06.29 |