ASP.NET Core 项目分层的第一个接口实现(基于Net.Core 3.1和Visual Studio 2019)

添加实体模型

在项目根目录下新建Models文件夹,在这里可以创建实体类

using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFGetStarted.Models
{
    public class Company
    {
        [Key] //主键 
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //设置自增
        public int Id { get; set; }

        
        [Required] // 非空
        [Column(TypeName = "varchar(200)")] // 设置字段类型
        [Comment("公司名称")] // 列注释
        public string CompanyName { get; set; }

        // 创建时间
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public DateTime Inserted { get; set; }

        // 插入或更新时间
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime LastUpdated { get; set; }
    }
}
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


namespace EFGetStarted.Models
{
    public class Employee
    {
        [Key] //主键 
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //设置自增
        public int Id { get; set; }


        [Required] // 非空
        [Column(TypeName = "varchar(200)")] // 设置字段类型
        [Comment("员工姓名")] // 列注释
        public string Name { get; set; }

        [Required] // 非空
        [Comment("性别")] // 列注释
        public bool Sex { get; set; }

        [ForeignKey("company")] //外键
        public int CompanyId { get; set; }
        public Company company { get; set; }


        // 创建时间
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public DateTime Inserted { get; set; }

        // 插入或更新时间
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime LastUpdated { get; set; }
    }
}

添加数据库上下文

新建Data文件夹,在其中添加数据库上下文

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

在数据库上下文中注册模型

using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;

namespace EFGetStarted.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Company> companies { get; set; }
        public DbSet<Employee> employees { get; set; }
    }
}

配置数据库

appsettings.json添加如下内容

"ConnectionStrings": {
    "MysqlConnection": "Data Source=127.0.0.1;Database=ef-mysql-api;User ID=root;Password=123456789;pooling=true;port=3306;sslmode=none;CharSet=utf8;"
  },

修改Startup.cs

// 将服务添加到DI容器中
public void ConfigureServices(IServiceCollection services)
{
    // 读取数据库连接字符串
    var connection = Configuration.GetConnectionString("MysqlConnection");
    // 注册数据库上下文
    services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connection));
    services.AddControllers();
}

迁移数据库

Powershell中执行

dotnet ef migrations add first

使用如下命令将表结构同步到数据库

dotnet ef database update

添加Service层

在项目根目录下新建Service文件夹,在这里可以创建Service类

新建CompanyService

using EFGetStarted.Data;
using EFGetStarted.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EFGetStarted.Services
{
    public class CompanyService
    {

        public ApplicationDbContext Context;

        public CompanyService(ApplicationDbContext context)
        {
            Context = context;
        }

        public async Task<List<Company>> GetCompanys()
        {
            var companys = await Context.companies.ToListAsync();
            return companys;
        }   
    }
}

在DI容器中注册该Service

// 将服务添加到DI容器中
public void ConfigureServices(IServiceCollection services)
{
    // 读取数据库连接字符串
    var connection = Configuration.GetConnectionString("MysqlConnection");
    // 注册数据库上下文
    services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(connection));
    // 注册Service
    services.AddScoped<CompanyService>();
    services.AddControllers();
}

新建Controller层

在项目根目录下新建Controller文件夹,在这里可以创建Controller类

新建CompaniesController

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using EFGetStarted.Models;
using EFGetStarted.Services;
using System.Threading.Tasks;

namespace EFGetStarted.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CompaniesController : ControllerBase
    {
        private readonly CompanyService _companyService;

        public CompaniesController(CompanyService companyService)
        {
            _companyService = companyService;
        }

        // GET: api/Companies
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Company>>> Getcompanies()
        {
            return await _companyService.GetCompanys();
        }
    }
}

访问https://localhost:5001/api/Companies即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值