asp.net core 3.1使用EFCore

1.增加一个实体类

/// <summary>
    /// 团队成员模型
    /// </summary>
    public class Member
    {
        /// <summary>
        /// 团队成员主键
        /// </summary>
        public int Id { set; get; }
        /// <summary>
        /// 团队成员名
        /// </summary>
        public string FirstName { set; get; }
        /// <summaryhua
        /// 团队成员花名
        /// </summary>
        public string NickName { set; get; }

        /// <summary>
        /// 团队主键
        /// </summary>
        public int TeamId { set; get; }
    }

2.增加一个数据库上下文实体

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

        public DbSet<Member> Members { get; set; }
    }

3.注册上下文到IOC容器

     public void ConfigureServices(IServiceCollection services)
        {
            // 1、注册上下文到IOC容器
            services.AddDbContext<MemberContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
        }

4.appsettings.json 添加数据库配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=memberservice;Persist Security Info=True;User ID=sa;Password=tony"
  }
}

5.安装EF Core 命令行工具

dotnet tool install --global dotnet-ef

6.安装NuGet包 Microsoft.EntityFrameworkCore.Design

7.增加初始化迁移,更新数据库

执行命令

dotnet ef migrations add test

执行成功后,在项目中会生成脚本操作

执行命令

dotnet ef database update

执行成功后,生成数据库

8.添加服务接口

    public interface IMemberService
    {
        IEnumerable<Member> GetMembers();
        IEnumerable<Member> GetMembers(int teamId);
    }

9.添加服务实现

    public class MemberServiceImpl : IMemberService
    {
        public readonly IMemberRepository memberRepository;
        public IEnumerable<Member> GetMembers()
        {
            return memberRepository.GetMembers();
        }
        public IEnumerable<Member> GetMembers(int teamId)
        {
            return memberRepository.GetMembers(teamId);
        }
    }

10.添加仓储接口

    public interface IMemberRepository
    {
        IEnumerable<Member> GetMembers();
      
        IEnumerable<Member> GetMembers(int teamId);
    
    }

11.添加仓促实现

    public class MemberRepository : IMemberRepository
    {
        public MemberContext teamContext;
        public MemberRepository(MemberContext teamContext)
        {
            this.teamContext = teamContext;
        }
      
        public IEnumerable<Member> GetMembers()
        {
            return teamContext.Members.ToList();
        }

        public IEnumerable<Member> GetMembers(int teamId)
        {
            return teamContext.Members.Where(memeber => memeber.TeamId == teamId);
        }
    }

12.注册service和仓促

     public void ConfigureServices(IServiceCollection services)
        {
            // 1、注册上下文到IOC容器
            services.AddDbContext<MemberContext>(opt =>
           opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  //使用SqlServer数据库

            // 2、注册成员service
            services.AddScoped<IMemberService, MemberServiceImpl>();

            // 3、注册成员仓储
            services.AddScoped<IMemberRepository, MemberRepository>();

            services.AddControllers();
        }

13.添加Controller

    [Route("api/[controller]")]
    [ApiController]
    public class MembersController : ControllerBase
    {
        private readonly IMemberService memberService;

        public MembersController(IMemberService memberService)
        {
            this.memberService = memberService;
        }
        /// <summary>
        /// 查询所有成员信息
        /// </summary>
        /// <param name="teamId">?teamId参数结尾方式</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<Member>> GetMembers(int teamId)
        {
            if (teamId == 0)
            {
                return memberService.GetMembers().ToList();
            }
            else
            {
                return memberService.GetMembers(teamId).ToList();
            }
        }
    }

14.查看运行结果

 

posted @ 2020-09-20 16:18  王大师123  阅读(1846)  评论(1编辑  收藏  举报