ASP.NET Core 如何使用Mvc相关技术建立Controller、Tag Helper (上)

使用Mvc相关技术来完善一下前几篇文章的小栗子。。。

  • Controller
  • Tag Helper
  • Settings
  • View Component
  • Razor Page

首先添加一个Model文件夹

Department部门类(1):

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

namespace WebApplication1.Models
{
    public class Department
    {
        public int Id { get; set; }
        [Display(Name ="部门名称")]
        public string Name { get; set; }
        public string Location { get; set; }
        public int EmployeeCount { get; set; }
    }
}

 Employee员工类(多):

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

namespace WebApplication1.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public int DepartmentId { get; set; } //外键
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Gender Gender { get; set; }
        public bool Fired { get; set; }
    }

    public enum Gender
    { 
        女=0,
        男=1
    }
}

CompanySummary类:统计员工总数以及每个部门平均员工数量

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

namespace WebApplication1.Models
{
    /// 
    /// 公司
    /// 
    public class CompanySummary
    {
        //员工总数
        public int EmployeeCount { get; set; }
        //部门平均员工数量
        public int AverageDepartmentEmployeeCount { get; set; }
    }
}

添加一个Services文件夹,在文件夹里面添加两个服务。

一个是IDepartmentService接口,一个是IEmployeeService接口

IDepartmentService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public interface IDepartmentService
    {
        //获取所有部门
        Task> GetAll();
        //通过Id获取部门
        Task GetById(int id);
        Task GetCompanySummary();
        //添加部门
        Task Add(Department department);
    }
}

接下来就是实现这两个接口!同样是在Services文件夹里面添加对应的实现接口的两个类

DepartmentService类:

首先将定义的departmentService类继承接口IDepartmentService 实现接口方法 。

通过readonly定义一个只读的List集合,在构造数里面添加几条部门数据。

GetAll()方法:返回类型为Task。这里涉及到了C#的异步编程。

GetById():根据部门Id进行查询。

GetCompanySummary():查询部门总人数以及每个部门的平均人数

Add():新增,将新增的Id在部门最大Id+1即可。

写到这里呢,就是一套服务了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public class DepartmentService:IDepartmentService
    {
        private readonly List _departments = new List();
        public DepartmentService()
        {
            _departments.Add(new Department
            {
                Id=1,
                Name="HR",
                EmployeeCount=16,
                Location="北京"
            });
            _departments.Add(new Department
            {
                Id = 2,
                Name = "HR1",
                EmployeeCount = 52,
                Location = "上海"
            });
            _departments.Add(new Department
            {
                Id = 3,
                Name = "HR2",
                EmployeeCount = 200,
                Location = "广州"
            });
        }

        public Task> GetAll()
        {
            return Task.Run(()=>_departments.AsEnumerable());
        }
        public Task GetById(int id)
        {
            return Task.Run(() => _departments.FirstOrDefault(x => x.Id == id));
        }

        public Task GetCompanySummary()
        {
            return Task.Run(() =>
            {
                return new CompanySummary
                {
                    EmployeeCount = _departments.Sum(x => x.EmployeeCount),
                    AverageDepartmentEmployeeCount = (int)_departments.Average(x => x.EmployeeCount)
                };
            });
        }
        public Task Add(Department department)
        {
            //现有部门最大Id+1就是最新Id
            department.Id = _departments.Max(x => x.Id) + 1;
            _departments.Add(department);
            return Task.CompletedTask;
        }
    }
}

IEmployeeService:接下来也是一套服务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public interface IEmployeeService
    {
        Task Add(Employee employee);
        Task> GetByDepartmentId(int departmentId);
        Task Fire(int id);
    }
}

EmployeeService类:这个类里面的方法和部门类的方法基本上差不多,也都是返回Task。

GetByDepartmentId():根据部门Id查询该部门所有人员。

Add():一样也是做新增员工操作。

Fire():这个方法主要是负责员工是否已离职,离职:False、在职:True(默认)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public class EmployeeService : IEmployeeService
    {
        private readonly List _employees = new List();

        public EmployeeService()
        {
            _employees.Add(new Employee
            {
                Id=1,
                DepartmentId=1,
                FirstName="Nick",
                LastName="Carter",
                Gender=Gender.男
            });
            _employees.Add(new Employee
            {
                Id = 2,
                DepartmentId = 1,
                FirstName = "Michael",
                LastName = "Jackson",
                Gender = Gender.男
            });
            _employees.Add(new Employee
            {
                Id = 3,
                DepartmentId = 1,
                FirstName = "Mariah",
                LastName = "Carey",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 4,
                DepartmentId = 2,
                FirstName = "Avril",
                LastName = "CarLavigneter",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 5,
                DepartmentId = 3,
                FirstName = "小希",
                LastName = "",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 6,
                DepartmentId = 3,
                FirstName = "小伟",
                LastName = "",
                Gender = Gender.男
            });
        }

        public Task Add(Employee employee)
        {
            employee.Id = _employees.Max(x => x.Id) + 1;
            _employees.Add(employee);
            return Task.CompletedTask;
        }

        public Task Fire(int id)
        {
            return Task.Run(() =>
            {
                var employee = _employees.FirstOrDefault(e => e.Id == id);
                if (employee != null)
                {
                    employee.Fired = true;
                    return employee;
                }
                return null;
            });
        }

        public Task> GetByDepartmentId(int departmentId)
        {
            return Task.Run(() => _employees.Where(x=>x.DepartmentId==departmentId));
        }
    }
}

这两套服务搞定后,就是注册这两套服务了。。。

去到Startup类:

public void ConfigureServices(IServiceCollection services)
{
     //负责配置依赖注入
     //DI 依赖注入机制依赖于IOC容器(控制反转)
     //使用Asp.NET Core MVC,所有需要通道控制器和视图要进行注册一下m\v\c(通过services服务注册)
     services.AddControllersWithViews();

     //分别注册服务
     services.AddSingleton();
     services.AddSingleton();
}

 

你可能感兴趣的:(ASP.NET Core 如何使用Mvc相关技术建立Controller、Tag Helper (上))