Vs2017 NetCode Mvc EF Mysql 整合2



  • 1 NetCode EF整合 代码

    1.1 项目文件结构

    1.2 NuGet MySql.Data.EntityFrameworkCore 8.0.18

    1.3 appsettings.json 增加数据库字符串链接ConnectionStrings

    {
       "Logging": {
           "IncludeScopes": false,
           "LogLevel": {
               "Default": "Warning"
           }
       },
       "ConnectionStrings": { "MysqlConnection": "Data Source=localhost;Database=demodb;User ID=root;Password=root;pooling=true;CharSet=utf8;port=3306;sslmode=none" }
    }
    

    1.4 DBEntities.cs 添加数据库上下文

    using EFMysqlNetCodeMvc.Models;
    using Microsoft.EntityFrameworkCore;
    
    namespace EFMysqlNetCodeMvc
    {
       public class DBEntities : DbContext
       {
           public DBEntities(DbContextOptions<DBEntities> options) : base(options)
           {
           }
    
           ////这里也可以
           //string str = @"Data Source=localhost;Database=demodb;User ID=root;Password=root;pooling=true;CharSet=utf8;port=3306;sslmode=none";
    
           //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
           //    optionsBuilder.UseMySQL(str);
    
           public DbSet<User> User { get; set; }
       }
    }
    

    1.5 User.cs 增加数据库表实体类

    1.6 Startup.cs 配置重点 有中文注释的新加的

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using EFMysqlNetCodeMvc;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Newtonsoft.Json.Serialization;
    
    namespace EFMysqlNetCodeMvc
    {
       public class Startup
       {
           public Startup(IConfiguration configuration)
           {
               Configuration = configuration;
           }
    
           public IConfiguration Configuration { get; }
    
           // This method gets called by the runtime. Use this method to add services to the container.
           public void ConfigureServices(IServiceCollection services)
           {
               //json格式化
               services.AddMvc()
               .AddJsonOptions(options =>
               {
                   //忽略循环引用
                   //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    
                   //设置序列化时key为驼峰样式,开头字母小写输出  controller调用Josn(对象)
                   options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                   //原样输出
                   //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    
                   //时间格式
                   options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    
                   //空值的字段不显示
                   //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
               });
    
               //ef mysql 配置IOC
               services.AddDbContext<DBEntities>(options => options.UseMySQL(Configuration.GetConnectionString("MySqlConnection")));
               services.AddMvc();
           }
    
           // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
           public void Configure(IApplicationBuilder app, IHostingEnvironment env)
           {
               if (env.IsDevelopment())
               {
                   app.UseBrowserLink();
                   app.UseDeveloperExceptionPage();
               }
               else
               {
                   app.UseExceptionHandler("/Home/Error");
               }
    
               app.UseStaticFiles();
    
               // 跨域策略
               app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
    
               //app.UseMvc();
               app.UseMvc(routes =>
               {
                   routes.MapRoute(
                       name: "default",
                       template: "{controller=Home}/{action=Index}/{id?}");
               });
           }
       }
    }
    

    1.7 HomeController.cs mvc 代码用于测试

    public class HomeController : Controller{
    

    DBEntities db;

    public HomeController(DBEntities db)
    {
    this.db = db;
    }

           public IActionResult Test()
           {
             
               //查询
               List<User> list = db.User.ToList();
               
               //json序列化
               //var userJson = JsonConvert.SerializeObject(list);
               //var userList = JsonConvert.DeserializeObject<List<User>>(userJson);
    
               return Json(list);
           }
    
           public IActionResult Add([FromBody] User user)
           {
               //新增
               //User user = new User();
               //user.Id = Guid.NewGuid().ToString().Replace("-", "");
               //db.User.Add(user);
               //db.SaveChanges();
    
               return Json(user);
           }}
    

    1.8 运行结果

    1.9 重点代码说明

    1.9.1 URL:/home/test 实体User.cs首字母大写 输出首字母变小写

               //json格式化
               services.AddMvc()
               .AddJsonOptions(options =>
               {
                   //忽略循环引用
                   //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    
                   //设置序列化时key为驼峰样式,开头字母小写输出  controller调用Josn(对象)
                   options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                   //原样输出
                   //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    
                   //时间格式
                   options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    
                   //空值的字段不显示
                   //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
               });
    

    1.9.2 URL:/home/add 输入参数首字母小写 自动转化为实体User.cs首字母大写

    public IActionResult Add([FromBody] User user)

    2.0 User.cs

    using System;
    
    namespace EFMysqlNetCodeMvc.Models
    {
       /// <summary>
       /// 账号表
       /// </summary>
       public class User
       {
           /// <summary>
           /// 
           /// </summary>   
           public string Id { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string TenantId { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string UserName { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string RealName { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string UserCode { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Password { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Salt { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Mobile { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Email { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public int UserType { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public int Status { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Creator { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public DateTime CreateTime { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string Reviser { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public DateTime ReviseTime { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public DateTime? LoginTime { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string IP { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public DateTime? LastLoginTime { get; set; }
           /// <summary>
           /// 
           /// </summary>   
           public string LastIP { get; set; }
       }
    }
    

    来自:https://www.cnblogs.com/chxl800/p/11724894.html



最新帖子

推荐阅读