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();
        }
    }
}

@陈卧龙的博客

 

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