.net core 2.2 EF oracle db first

Nuget控制台:

Install-Package log4net
Install-Package Newtonsoft.Json
Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection
Install-Package AutoMapper
Install-Package Dapper
Install-Package Microsoft.Extensions.Options
Install-Package Microsoft.Extensions.Caching.Abstractions
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Install-Package Oracle.EntityFrameworkCore
Install-Package Oracle.ManagedDataAccess.Core

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Relational
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.Tools


Scaffold-DbContext -Force "Data Source=" Oracle.EntityFrameworkCore-OutputDir Models/DataModels -Context MyDbContext -Schemas aaa -Tables bbb 

  

 

Scaffold命令格式:

Scaffold-DbContext [-Connection] <String> [-Provider] <String>
[-OutputDir <String>] [-Context <String>] [-Schemas <String>]
[-Tables <String>] [-DataAnnotations] [ -Force] [-Project <String>]
[-StartupProject <String>] [-Environment <String>] [<CommonParameters>]

Startup.cs

 public class Startup
    {
        //log4net日志
        public static ILoggerRepository LogRepository { get; set; }
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            Init();
        }
        public void Init()
        {
            // 加载log4net日志配置文件
            LogRepository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
            LogHelper.RepositoryName = LogRepository.Name;

            // appSettings 配置类初始化
            //ConfigHelper.Init(Configuration.GetSection("appSettings"));

            // 唯一Id生成器
            //SnowflakeInit.Init(Configuration);      
            
            // 邮件初始化
            //MailInit.Init(Configuration);

            // 系统启动日志
            LogHelper.Write("TestApi Start()");
        }

        /// <summary>
        /// 此方法由运行时调用。使用此方法向容器添加服务。
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {           
            //注册Cookie认证服务
            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

            // 添加MemoryCache
            services.AddMemoryCache();
            // 支持HttpContext
            services.AddHttpContextAccessor();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // 实现小写的路由URL
            services.AddRouting(options => options.LowercaseUrls = true);
            // 添加自动映射
            //services.AddAutoMapper();

            // 对 JSON 数据使用混合大小写。驼峰式,但是javascript 首字母小写形式. 默认值
            // services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); });
            services.AddMvc().AddJsonOptions(options =>
            {
                // 忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                // 对 JSON 数据使用混合大小写。跟属性名同样的大小.输出
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                // 格式化json日期           
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'fff" });
                // long型转string           
                options.SerializerSettings.Converters.Add(new Utils.LongToStringConverter());
            });

            //配置跨域处理,允许所有来源:
            services.AddCors(options =>
            {
                options.AddPolicy("cors", set =>
                {
                    set.SetIsOriginAllowed(origin => true). //允许任何来源的主机访问
                    AllowAnyHeader().
                    AllowAnyMethod().
                    AllowCredentials(); //指定处理cookie
                });
            });

            // 添加EF Oracle支持
            services.AddDbContext<MyDbContext>(options => options.UseOracle(Configuration.GetConnectionString("OracleConnectionString")));
            // 如果使用SQL Server 2008数据库,请添加UseRowNumberForPaging的选项
            // 参考资料:https://github.com/aspnet/EntityFrameworkCore/issues/4616
            // options.UseSqlServer(Configuration.GetConnectionString("MyDbContent"),b=>b.UseRowNumberForPaging())

            // 添加Dapper
            //services.AddDapper("OracleConnection", options =>
            //{
            //    options.ConnectionString = Configuration.GetConnectionString("OracleConnectionString");
            //    options.DbType = DbStoreType.Oracle;
            //});
          
            // Add service filters.
            //services.AddScoped<MyAuthAttribute>();
            //services.AddSingleton<MyAuthRepository>();

            //注入全局异常捕获
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(GlobalExceptions)); // By type
            });           
           
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // 注册Autofac
            return RegisterAutofac(services);
        }
        private IServiceProvider RegisterAutofac(IServiceCollection services)
        {
            //实例化Autofac容器
            var builder = new ContainerBuilder();
            //将Services中的服务填充到Autofac中
            builder.Populate(services);
            //新模块组件注册    
            builder.RegisterModule<AutofacModule>();
            //创建容器
            var Container = builder.Build();
            //第三方IOC接管 core内置DI容器 
            return new AutofacServiceProvider(Container);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseCors("cors");
            app.UseMvc();

            //程序停止调用函数
            //appLifetime.ApplicationStopped.Register(() => { AutofacContainer.Dispose(); });
        }
    }

  Program:

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
                                        .AddJsonFile("host.json")
                                        .Build();

            return WebHost.CreateDefaultBuilder(args)
                .UseUrls(configuration["urls"])
                .UseStartup<Startup>();
        }
    }

  host.json

{
  "urls": "http://*:8080;https://*:443"
}

  AutofacModule

 public class AutofacModule : Autofac.Module
    {
        /// <summary>
        /// 重写Autofac管道Load方法,在这里注册注入
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<MyDbContext>();

            //注册Service中的对象,Service中的类要以Service结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WebTest.BLL")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
  
            //注册Repository中的对象,Repository中的类要以Repository结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WebTest.DAL")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();
        }
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static System.Reflection.Assembly GetAssemblyByName(string AssemblyName)
        {
            return System.Reflection.Assembly.Load(AssemblyName);
        }
    }

 Utils.LongToStringConverter.cs

public class LongToStringConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Newtonsoft.Json.Linq.JToken jt = Newtonsoft.Json.Linq.JValue.ReadFrom(reader);
            return jt.Value<long>();
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(System.Int64).Equals(objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value.ToString());
        }
    }

  

 

 

posted @ 2019-08-20 13:50  轮回  阅读(650)  评论(0编辑  收藏  举报