728x90
728x170

Entity Framework Core 로 Sqlite 사용하는 방법입니다.
1. 'Microsoft.EntityFrameworkCore.Sqlite' Nuget Package 를 설치합니다.
    (그새 버전이 올랐네요)

 
2. 테이블 구조를 정의합니다.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

Id 필드는 키로 정의됩니다. 그렇지 않고 다른 필드를 키고 잡고 싶은 경우 [Key] 로 정의하면됩니다.

public class Employee
{
    [Key]
    public string Name { get; set; }
    public int Age { get; set; }
}

 
 
3. DbContext 를 이용해 db 파일 지정하고 DbSet<Table> 필드를 만듭니다.
   (DbSet<Table> 필드는 CRUD 에 사용합니다.)

public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=mydb.db");
    }
}

 
4. 사용하는 방법
신규 항목을 추가하는 코드

using (var db = new MyDbContext())
{
    db.Database.EnsureCreated();

    var employee = new Employee { Name = "Kang Jun", Age = 40 };
    db.Employees.Add(employee);
    db.SaveChanges();
}

 
전체코드

using System.ComponentModel.DataAnnotations;

using Microsoft.EntityFrameworkCore;

namespace EFTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MyDbContext())
            {
                db.Database.EnsureCreated();

                var employee = new Employee { Name = "Kang Jun", Age = 40 };
                db.Employees.Add(employee);
                db.SaveChanges();
            }
        }

        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public class Employee2
        {
            [Key]
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public class MyDbContext : DbContext
        {
            public DbSet<Employee> Employees { get; set; }
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlite("Filename=mydb.db");
            }
        }
    }
}

 
결과

 

728x90
그리드형
Posted by kjun
,