09_EntityFrameworkCore 6 简单使用

1. 首先我们先用vs2022 创建一个WebAPI

添加安装包:

Microsoft.EntityFrameworkCore.SqlServer 

Microsoft.EntityFrameworkCore.Tools

 

2.添加一个类用于测试

/// <summary>
    /// 用户信息
    /// </summary>
    public class UserInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Username { get; set; }

    }

 

3.创建一个Context类,需要继承DbContext

public class EfContext : DbContext
    {
        public EfContext(DbContextOptions<EfContext> options) : base(options)
        {

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

        /*
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);//加载程序集配置
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            string _sql = "server=LAPTOP;uid=sa;pwd=123456;database=EFCore_Db";
            optionsBuilder.UseSqlServer(_sql);
        }
        */
    }

 

4.配置appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ServerSql": "server=LAPTOP;uid=sa;pwd=123456;database=EFCore_Db",
    "MySql": ""
  }
}

 

5.Program.cs注册EfContext,有两种方式

#region EfContext
            builder.Services.AddDbContext<EfContext>(p =>
            {
                p.UseSqlServer(builder.Configuration.GetConnectionString("ServerSql"));
            });
//通过工厂方式 builder.Services.AddDbContextFactory<EfContext>(p => { p.UseSqlServer(builder.Configuration.GetConnectionString("ServerSql")); }); #endregion

6.生产项目后在管理器控制台内 分别执行:Add-Migration 和 Update-Database

常用的一些命令:

     Add-Migration               添加新的迁移
     Drop-Database               删除数据库
     Get-DbContext               获取有关DbContext类型的信息
     Remove-Migration            删除上一次迁移
     Scaffold-DbContext          搭建数据库的DbContext和实体类型
     Script-Migration            从迁移生成SQL脚本
     Update-Database             将数据库更新为指定的迁移

 

7.测试(实现增删改查)

[Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {        private EfContext _efContext;
        private IDbContextFactory<EfContext> _dbContext;//通过工厂方式

        public UserController(
            EfContext efContext,
            IDbContextFactory<EfContext> dbContext)
        {this._efContext = efContext;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public UserInfo AddUserInfo()
        {
            UserInfo userInfo = new UserInfo()
            {
                Name = "李四",
                Email = "1234@qq.com",
                Password = "123456",
                Username = "小四"
            };
            var res = _efContext.UserInfo.Add(userInfo);

            _efContext.SaveChanges();
            _efContext.Dispose();
            return userInfo;
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public List<UserInfo> GetUerInfo(int id)
        {
            List<UserInfo> userInfos = new List<UserInfo>();
           
            var res = _efContext.UserInfo.Where(p => p.Id == id);
            foreach (var item in res)
            {
                userInfos.Add(item);
            }
            _efContext.Dispose();


            using (var dbx = _dbContext.CreateDbContext())
            {
                UserInfo? info = dbx.UserInfo.FirstOrDefault(p => p.Id == id);
                userInfos.Add(info);
            }

               return userInfos;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public UserInfo UpdateUerInfo(int id, string uName)
        {
            var res = _efContext.UserInfo.FirstOrDefault(p => p.Id == id);
            res.Username = uName;

            _efContext.UserInfo.Update(res);
            _efContext.SaveChanges();
            _efContext.Dispose();
            return res;
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public UserInfo DeleteUerInfo(int id)
        {
            var res = _efContext.UserInfo.FirstOrDefault(p => p.Id == id);

            _efContext.UserInfo.Remove(res);
            _efContext.SaveChanges();
            _efContext.Dispose();
            return res;
        }
    }

 

posted @ 2018-02-09 11:49  野码  阅读(13399)  评论(2编辑  收藏  举报