欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ASP.Net Core Web Api + EFCore

程序员文章站 2022-07-03 08:49:48
...

ASP.Net Core Web Api + EFCore

项目结构:
ASP.Net Core Web Api + EFCore
Controllers控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JTestWeb.Entities;
using JTestWeb.Models;
using JTestWeb.Services;
using Microsoft.AspNetCore.Mvc;

namespace JTestWeb.Controllers
{
    [ApiController]
    [Route("api/userinfos")]
    public class UserInfosController : ControllerBase
    {
        private readonly IUserInfoRepository _userInfoRepository;
        public UserInfosController(IUserInfoRepository userInfoRepository)
        {
            _userInfoRepository = userInfoRepository
                ?? throw new ArgumentNullException(nameof(userInfoRepository));
        }

        //查询所有用户
        [HttpGet]//"api/companies"
        public async Task<ActionResult<IEnumerable<UserInfoDto>>> GetUserInfos()
        {
            //模拟抛出异常
            //throw new Exception("An Exception");

            var userInfos = await _userInfoRepository.GetUserInfosAsync();

            //Entity Model  VS 对外的Model
            var userInfoDtos = new List<UserInfoDto>();
            foreach (var userInfo in userInfos)
            {
                userInfoDtos.Add(new UserInfoDto
                {
                    Name = userInfo.Name,
                    Identity = userInfo.Identity,
                    Gender = userInfo.Gender,
                    Address = userInfo.Address,
                    Phone = userInfo.Phone,
                    Email = userInfo.Email,
                    RegistTime = userInfo.RegistTime
                });
            }

            //return new JsonResult(companies);
            return Ok(userInfoDtos);
        }

        //根据用户名查询某个用户
        [HttpGet("{name}",Name = nameof(GetUserInfo))]
        public async Task<IActionResult> GetUserInfo(string name)
        {
            var userInfo = await _userInfoRepository.GetUserInfoAsync(name);
            if(userInfo == null)
            {
                return NotFound();
            }
            var userInfoDto = new UserInfoDto()
            {
                Name = userInfo.Name,
                Identity = userInfo.Identity,
                Gender = userInfo.Gender,
                Address = userInfo.Address,
                Phone = userInfo.Phone,
                Email = userInfo.Email,
                RegistTime = userInfo.RegistTime
            };
            return Ok(userInfoDto);
        }

        //添加新用户
        [HttpPost]
        public async Task<ActionResult<UserInfoDto>> CreateUserInfo(UserInfoAddDto userInfo)
        {
            //if(company == null)
            //{
            //    return BadRequest();//返回400错误,现在控制器会自动返回,不用手动添加
            //}
            var entity = new UserInfo()
            {
                Name = userInfo.Name,
                Identity = userInfo.Identity,
                Gender = userInfo.Gender,
                Address = userInfo.Address,
                Phone = userInfo.Phone,
                Email = userInfo.Email,
                RegistTime = userInfo.RegistTime,
                Password = userInfo.Password
            };
            _userInfoRepository.AddUserInfo(entity);//.AddCompany(entity);
            await _userInfoRepository.SaveAsync();//保存数据到数据库

            var returnDto = new UserInfoDto()
            {  //此处将新添加的值返回,返回码201
                Name = userInfo.Name,
                Identity = userInfo.Identity,
                Gender = userInfo.Gender,
                Address = userInfo.Address,
                Phone = userInfo.Phone,
                Email = userInfo.Email,
                RegistTime = userInfo.RegistTime
            };

            //通过GetUserInfo(name)这个函数返回刚创建的用户信息
            return CreatedAtRoute(nameof(GetUserInfo), new { name = returnDto.Name }, returnDto);//第一个参数:路由名,第二个参数是路由的参数值
        }

        //改
        [HttpPut]
        //public async Task<ActionResult<UserInfoDto>> ModifyUserInfo(UserInfoAddDto userInfoDto)
        public async Task<ActionResult> ModifyUserInfo(UserInfoAddDto userInfoDto)
        {
            var userInfo = await _userInfoRepository.GetUserInfoAsync(userInfoDto.Name);
            if (userInfo == null)
            {
                return NotFound();
            }

            userInfo.Identity = userInfoDto.Identity;
            userInfo.Gender = userInfoDto.Gender;
            userInfo.Address = userInfoDto.Address;
            userInfo.Phone = userInfoDto.Phone;
            userInfo.Email = userInfoDto.Email;
            userInfo.RegistTime = userInfoDto.RegistTime;
            userInfo.Password = userInfoDto.Password;
            _userInfoRepository.UpdateUserInfo(userInfo);
            await _userInfoRepository.SaveAsync();//保存数据到数据库

            //return CreatedAtRoute(nameof(GetUserInfo), new { name = userInfo.Name },userInfo);//第一个参数:路由名,第二个参数是路由的参数值
            //return Ok();
            //return NotFound();
            return NoContent();
        }

        //删
        [HttpDelete("{name}")]
        public async Task<ActionResult> DeleteUserInfo(string name)
        {
            var userInfo = await _userInfoRepository.GetUserInfoAsync(name);
            if (userInfo == null)
            {
                return NotFound();
            }

            _userInfoRepository.DeleteUserInfo(userInfo);
            await _userInfoRepository.SaveAsync();

            return NoContent();
        }
    }
}

MyDbContext类:

using JTestWeb.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JTestWeb.Data
{
    public class MyDbContext:DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {

        }

        public DbSet<UserInfo> UserInfos { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserInfo>()
                .Property(x => x.Name).IsRequired().HasMaxLength(20);
            modelBuilder.Entity<UserInfo>()
                .Property(x => x.Password).IsRequired().HasMaxLength(20);
            modelBuilder.Entity<UserInfo>()
                .Property(x => x.Phone).IsRequired().HasMaxLength(20);

            modelBuilder.Entity<UserInfo>().HasData(
                new UserInfo
                {
                    Name = "Jerry",
                    Identity = "工作者",
                    Gender = "男",
                    Address = "安徽省池州师贵池区",
                    Phone = "18297491769",
                    Email = "aaa@qq.com",
                    RegistTime = "2020-10-17",
                    Password = "12345"
                });
        }
    }
}

Entities中的UserInfo类,这个类是和数据库对应的:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace JTestWeb.Entities
{
    public class UserInfo
    {
        [Key]
        public string Name { get; set; }
        public string Identity { get; set; }
        public string Gender { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string RegistTime { get; set; }
        public string Password { get; set; }
    }
}

Models模块的两个类:(这两个类是对外的添加新用户和展示用户信息的)
UserInfoAddDto类:

public class UserInfoAddDto
    {
        public string Name { get; set; }
        public string Identity { get; set; }
        public string Gender { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string RegistTime { get; set; }
        public string Password { get; set; }
    }

UserInfoDto类:

public class UserInfoDto
    {
        public string Name { get; set; }
        public string Identity { get; set; }
        public string Gender { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string RegistTime { get; set; }
    }

Services模块
IUserInfoRepository接口:

public interface IUserInfoRepository
    {
        //查询所有用户
        Task<IEnumerable<UserInfo>> GetUserInfosAsync();

        //根据用户名查询某个用户
        Task<UserInfo> GetUserInfoAsync(string name);

        //添加一个用户
        void AddUserInfo(UserInfo userInfo);

        //更新一个用户信息
        void UpdateUserInfo(UserInfo userInfo);

        //删除某个用户
        void DeleteUserInfo(UserInfo userInfo);

        //保存
        Task<bool> SaveAsync();
    }

UserInfoRepository类(实现数据库数据的增删改查):

public class UserInfoRepository : IUserInfoRepository
    {
        private readonly MyDbContext _context;

        public UserInfoRepository(MyDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        //查询所用用户
        public async Task<IEnumerable<UserInfo>> GetUserInfosAsync()
        {
            //throw new NotImplementedException();
            return await _context.UserInfos.ToListAsync();
        }

        //根据用户名查询某个用户
        public async Task<UserInfo> GetUserInfoAsync(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            return await _context.UserInfos.Where(x => x.Name == name).FirstOrDefaultAsync();
        }

        //添加新用户
        public void AddUserInfo(UserInfo userInfo)
        {
            //throw new NotImplementedException();
            if (userInfo == null)
            {
                throw new ArgumentNullException(nameof(userInfo));
            }

            _context.UserInfos.Add(userInfo);
        }

        //删除用户
        public void DeleteUserInfo(UserInfo userInfo)
        {
            //throw new NotImplementedException();
            if (userInfo == null)
            {
                throw new ArgumentNullException(nameof(userInfo));
            }
            _context.UserInfos.Remove(userInfo);
        }

        public async Task<bool> SaveAsync()
        {
            //throw new NotImplementedException();
            return await _context.SaveChangesAsync() >= 0;
        }

        public void UpdateUserInfo(UserInfo userInfo)
        {
            //throw new NotImplementedException();
            _context.Entry(userInfo).State = EntityState.Modified;
        }
    }

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JTestWeb.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace JTestWeb
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //var host = CreateHostBuilder(args).Build();
            //using (var scope = host.Services.CreateScope())
            //{
            //    try
            //    {
            //        var dbContext = scope.ServiceProvider.GetService<MyDbContext>();
            //        //先删除数据库中的数据
            //        //dbContext.Database.EnsureDeleted();
            //        dbContext.Database.EnsureCreated();
            //        //迁移数据库数据并产生三组数据
            //        dbContext.Database.Migrate();
            //    }
            //    catch (Exception ex)
            //    {
            //        var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
            //        logger.LogError(ex, "Database Migration Error!");
            //    }
            //}
            //host.Run();
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JTestWeb.Data;
using JTestWeb.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace JTestWeb
{
    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)
        {
            services.AddControllers();
            //services.AddControllers(setup =>
            //{
            //    setup.ReturnHttpNotAcceptable = true; //接收格式和请求格式不一致,返回406
            //    //setup.OutputFormatters.Add(new);//XmlDataContractSerializerOutFormatter()//添加格式
            //    //setup.OutputFormatters.Insert();//修改默认格式
            //}).AddXmlDataContractSerializerFormatters();//添加xml格式

            //每一次HTTP请求,会建立一个新的服务实例
            services.AddScoped<IUserInfoRepository, UserInfoRepository>();

            services.AddDbContext<MyDbContext>(option => {
                option.UseSqlServer(Configuration["Data:RoutineConnection:ConnectionString"]);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

appsetting.json(包含数据库的连接字符串)

{
  "Data": {
    "RoutineConnection": {
      "ConnectionString": "Server=LAPTOP-D0U21JQK;Database=JTestDB;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
相关标签: Web API EFCore