NetCore3.1 控制檯應用程序使用EfCore

十年河東,十年河西,莫欺少年窮

學無止境,精益求精

1、新建控制檯程序並添加項目引用

Install-Package Microsoft.EntityFrameworkCore -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.0
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 3.1.0
Install-Package Microsoft.Extensions.Configuration -Version 6.0.1

Install-Package Microsoft.Extensions.Hosting -Version 6.0.1
Install-Package Microsoft.Extensions.Hosting.WindowsServices -Version 6.0.0

說明,前四個引用和EfCore相關,後三個引用用於依賴注入,配置文件讀取及發佈爲windows服務

2、添加配置文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "WuAnDBContext": "Data Source=xxxx;Initial Catalog=WuAnDB;Password=xxx+#;User ID=sa;"
  },
  "myKey": "hello  windows  service",
  "RedisConnectionString": "127.0.0.1:6379,allowadmin=true"
}

3、增加數據庫上下文類庫WuAnDbContext,並引用EfCore相關包

Install-Package Microsoft.EntityFrameworkCore -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.0
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 3.1.0

 

 

 紅色框內兩個項目均需要引用上述四個包

5、執行腳本,生成數據庫上下文

注意,控制檯入庫程序所在項目須引用WuAnDbContext項目

Scaffold-DbContext "Data Source=xxx;Initial Catalog=WuAnDB;Password=xxxxx;User ID=sa;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Forc

6、代碼如下:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using WuAnDbContext.Models;
using wuanInterface;
using wuanService;

namespace BatteryOTA
{
    internal class Program
    {
        static string connectionString;
        static void Main(string[] args)
        {
            CreateHostBuilder(args).Run();
        } 

        public static IHost CreateHostBuilder(string[] args)
        { 
            var builder = Host.CreateDefaultBuilder(args).
                    ConfigureAppConfiguration((hostContext, configApp) =>
                    { 
                        var configuration = configApp.Build(); 
                        configApp.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                        connectionString= getDatabase(configuration);
                    }) 
                    .ConfigureServices((hostContext, services) =>
                    {
                        var basePath = Directory.GetCurrentDirectory();
                    #region SQLSERVER
                        services.AddDbContext<WuAnDBContext>(options =>
                         options.UseSqlServer(connectionString), ServiceLifetime.Transient);
                    #endregion
                        services.AddTransient<IBatteryService, BatteryService>();

                    }).UseWindowsService();
            var host = builder.Build();
            using (var serviceScope = host.Services.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                var myConfig = services.GetRequiredService<IConfiguration>();
                Console.WriteLine(myConfig.GetSection("mykey"));
                //
                var service = services.GetRequiredService<IBatteryService>();
                service.gettest();
            } 
            return host;
        }

        /// <summary>
        /// 獲取化數據庫配置
        /// </summary>
        /// <param name="configuration">應用程序配置</param>
        /// <returns></returns>
        public static string getDatabase(IConfigurationRoot configuration)
        {
            var connectionString = configuration.GetConnectionString("WuAnDBContext");
            return connectionString;

        }
    }
}
View Code

IBatteryService

    public interface IBatteryService
    {
        void gettest();
    }

BatteryService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WuAnDbContext.Models;
using wuanInterface;

namespace wuanService
{
    public class BatteryService: IBatteryService
    {
        protected readonly WuAnDBContext context;
        public BatteryService(WuAnDBContext context)
        {
            this.context = context;
        }
        public void gettest()
        {
            var s = context.BaseBattery.Where(A => A.BatteryNo.Contains("312")).ToArray();
        }
    }
}

@陳臥龍的博客

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章