.Net Core 3.0 Windows Form + Entity Framework Core + SQLite를 사용하고 싶습니다.

환경


  • Windows10 Pro (1903) 64bit
  • Visual Studio 2019
  • .NET Core 3.0

  • 요약하면



    .NET Core 3.0에서 Windows Form이 지원되었습니다.
    ASP.NET Core에서 EF + SQLite를 할 수 있기 때문에 WinForm + EF + SQLite도 갈 수 있지? 라는 발상입니다.
    결론으로서 Core가 아닌 EF와 대략 같은 순서로 할 수 있었으므로 정리하고 있습니다.
    이미지가 많아서 비교적 길어졌습니다.

    접근



    .NET Core Windows Form App 프로젝트 구축




    Windows Forms App (.NET Core)이라는 꽤 그림

    Model, DbContext 등을 별도의 DLL로 정리






    이런 느낌의 프로젝트 구성입니다.
    WinFormCoreAppTest에서 EFCoreTest를 참조 설정합니다.

    Entity Framework Core 설치



    Nuget에서 설치합니다.
    Microsoft.EntityFramework.Core.SQLite

    Microsoft.EntityFramework.Core.Tools


    DLL 측 프로젝트에 다양한 클래스 추가



    모델

    Product.cs
    namespace EFCoreTest
    {
        public class Product
        {
            [Key]
            public string ProductId { get; set; }
    
            public int UnitPrice { get; set; }
    
            public string Name { get; set; }
    
            public Product()
            {
                ProductId = Guid.NewGuid().ToString();
                UnitPrice = 0;
                Name = string.Empty;
            }
        }
    }
    

    컨텍스트

    SampleDbContext.cs
    namespace EFCoreTest
    {
        public class SampleDbContext : DbContext
        {
            /// <summary>
            /// サンプル用DbSet
            /// </summary>
            public DbSet<Product> Products { get; set; }
    
    
            public SampleDbContext() : base()
            {
            }
    
            public SampleDbContext(DbContextOptions options) : base(options)
            {
            }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlite("Data Source=sample.db");      //ここでDBファイルを指定
            }
        }
    }
    

    여기까지 하면 한번 빌드해 둡니다.

    Migration 클래스를 만들고 DB 파일을 만듭니다.



    명령을 실행합니다.
    add-migrations (Migration)
    

    이런 느낌의 로그가 나옵니다.


    할 수 있었습니다.

    InitialCreate.cs
    namespace EFCoreTest.Migrations
    {
        public partial class InitialCreate : Migration
        {
            protected override void Up(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.CreateTable(
                    name: "Products",
                    columns: table => new
                    {
                        ProductId = table.Column<string>(nullable: false),
                        UnitPrice = table.Column<int>(nullable: false),
                        Name = table.Column<string>(nullable: true)
                    },
                    constraints: table =>
                    {
                        table.PrimaryKey("PK_Products", x => x.ProductId);
                    });
            }
    
            protected override void Down(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.DropTable(
                    name: "Products");
            }
        }
    }
    

    나중에 Migration을 실제로 반영하므로 다음 명령을 실행합니다.
    update-database
    



    어라? WinFormCoreAppTest 쪽에 할 수 있었습니까?
    뭐 할 수 있으면 무엇이든 좋기 때문에 다음으로 진행합니다.

    Windows Form의 UI를 적당하게 만든다



    쉽게 컨트롤을 배치하여 화면을 만듭니다.
    .NET Core Windows Form에서의 UI 작성은 이번 기사의 취지가 아니기 때문에 은근하게 흘립니다.


    디폴트의 ​​아이콘이 약간 세련되고 되어 있다…

    CRUD 사용



    우선 샘플 데이터를 만들어 둡니다.
    이것이 표시되므로 Select는 OK.


    우선 Insert


    하단이 추가되었습니다.

    다음은 Update


    Sample2라는 사람이 업데이트되었습니다.

    마지막 Delete.


    Sample3은 녀석을 삭제했습니다.

    CRUD 전부 OK. 훌륭합니다.

    요약


  • .NET Framework Windows Form + Entity Framework (SQLServer)와 거의 같은 단계에서 SQLite 작업을 수행했습니다.
  • SQLite의 데이터베이스 파일을 어디에 할 수 있을까, 빌드시에 카피라든지 잊기 쉽다고 생각합니다.
  • Windows Form 앱이 되기 때문에 데이터베이스 파일이 유저의 환경에 놓여진다고 하는 것으로, 나중에 테이블 정의 바꾸는 경우는 별도로 사용하자.

  • 이상입니다.

    좋은 웹페이지 즐겨찾기