ABP框架之建立多表关系
本文以经典的 Student
表、Course
表和 SC
(学生课程关系表)表为示例,讨论如何在ABP框架中建立多对多的关系。
在关系型数据库中,我们知道 Student
和 Course
是多对多的关系,一个学生可以选多门课程,一门课程可以有多个学生,他们之间的关系通过 SC
表记录。下面我们就在ABP框架中实现这样的关系。
注:本文使用MySQL数据库,如何启动项目模板和更改数据库请看这里
注:已将demo上传到了Github,可以点击查看
1. 领域层建立实体
1.1 建立 Student
实体
实体
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using MyTest.StudentCourseRelationships;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.Students
{
public class Student : Entity<long>, IFullAudited
{
/// <summary>
/// 学号
/// </summary>
public string Number { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime? Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
public string IdCardNumber { get; set; }
/// <summary>
/// 学生与课程的关系
/// </summary>
public ICollection<StudentCourseRelationship> SC { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
}
}
设置字段大小常量
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.Students
{
public class StudentConsts
{
public const int MaxNameLength = 16;
public const int MaxSexLength = 4;
public const int MaxNumberLength = 32;
public const int MaxIdCardNumberLength = 32;
}
}
1.2 建立 Course
实体
实体
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyTest.StudentCourseRelationships;
namespace MyTest.Courses
{
public class Course : Entity<long>, IFullAudited
{
/// <summary>
/// 课程编号
/// </summary>
public string Number { get; set; }
/// <summary>
/// 课程名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 课程学分
/// </summary>
public int Credit { get; set; }
/// <summary>
/// 备注
/// </summary>
public string remark { get; set; }
/// <summary>
/// 课程与学生的关系
/// </summary>
public ICollection<StudentCourseRelationship> SC { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
}
}
设置字段大小常量
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.Courses
{
public class CourseConsts
{
public const int MaxNumberLength = 16;
public const int MaxNameLength = 32;
public const int MaxRemarkLength = 200;
public const int MaxCreditLength = 8;
}
}
1.3 建立学生与课程关系表 StudentCourseRelationship
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using MyTest.Courses;
using MyTest.Students;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.StudentCourseRelationships
{
public class StudentCourseRelationship : Entity<long>, ICreationAudited, IDeletionAudited, ISoftDelete
{
/// <summary>
/// 学生学号
/// </summary>
public long StudentId { get; set; }
/// <summary>
/// 课程号
/// </summary>
public long CourseId { get; set; }
/// <summary>
/// 课程成绩
/// </summary>
public int? Grade { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
public bool IsDeleted { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
long? IDeletionAudited.DeleterUserId { get; set; }
DateTime? IHasDeletionTime.DeletionTime { get; set; }
}
}
2. 基础设施层更新数据库
using Microsoft.EntityFrameworkCore;
using Abp.Zero.EntityFrameworkCore;
using MyTest.Authorization.Roles;
using MyTest.Authorization.Users;
using MyTest.MultiTenancy;
using MyTest.Students;
using MyTest.Courses;
using MyTest.StudentCourseRelationships;
namespace MyTest.EntityFrameworkCore
{
public class MyTestDbContext : AbpZeroDbContext<Tenant, Role, User, MyTestDbContext>
{
/* Define a DbSet for each entity of the application */
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourseRelationship> SC { get; set; }
public MyTestDbContext(DbContextOptions<MyTestDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Student>(b =>
{
b.ToTable("Students");
b.Property(x => x.Name).IsRequired().HasMaxLength(StudentConsts.MaxNameLength);
b.Property(x => x.Sex).IsRequired().HasMaxLength(StudentConsts.MaxSexLength);
b.Property(x => x.Number).IsRequired().HasMaxLength(StudentConsts.MaxNumberLength);
b.Property(x => x.IdCardNumber).HasMaxLength(StudentConsts.MaxIdCardNumberLength);
b.HasIndex(x => x.Number);
b.HasIndex(x => x.Name);
b.HasIndex(x => x.IdCardNumber);
});
modelBuilder.Entity<Course>(b =>
{
b.ToTable("Courses");
b.Property(x => x.Name).IsRequired().HasMaxLength(CourseConsts.MaxNameLength);
b.Property(x => x.Number).IsRequired().HasMaxLength(CourseConsts.MaxNumberLength);
b.Property(x => x.remark).HasMaxLength(CourseConsts.MaxRemarkLength);
b.Property(x => x.Credit).IsRequired().HasMaxLength(CourseConsts.MaxCreditLength);
});
modelBuilder.Entity<StudentCourseRelationship>(b =>
{
b.ToTable("SC");
/// <summary>
/// 设置字段 `StudentId` 和 `CourseId` 为外键
/// </summary>
b.HasOne(x => x.Student).WithMany(x => x.SC).ForeignKey(x => x.StudentId);
b.HasOne(x => x.Course).WithMany(x => x.SC).ForeignKey(x => x.CourseId);
})
}
在程序包管理控制台依次执行下面命令
add-migration 'add_student_course_sc_table'
update-database
到此一个多对多的关系就建立好了,可以在数据库查看外键的设立是否正确。
3. 应用层创建应用服务
3.1 创建数据传输对象
3.1.1 有关 student
的传输对象
StudentDto
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.Students.Dto
{
public class StudentDto
{
/// <summary>
/// 学号
/// </summary>
public string Number { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime? Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
public string IdCardNumber { get; set; }
}
}
CreateStudentDto
using System;
using System.ComponentModel.DataAnnotations;
namespace MyTest.Students.Dto
{
public class CreateStudentDto
{
/// <summary>
/// 学号
/// </summary>
[Required]
[StringLength(32)]
public string Number { get; set; }
/// <summary>
/// 姓名
/// </summary>
[Required]
[StringLength(16)]
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
[StringLength(8)]
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime? Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
[StringLength(32)]
public string IdCardNumber { get; set; }
}
}
UpdateStudentDto
using Abp.Domain.Entities;
using System;
using System.ComponentModel.DataAnnotations;
namespace MyTest.Students.Dto
{
public class UpdateStudentDto : Entity<long>
{
/// <summary>
/// 学号
/// </summary>
[Required]
[StringLength(32)]
public string Number { get; set; }
/// <summary>
/// 姓名
/// </summary>
[Required]
[StringLength(16)]
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
[StringLength(8)]
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime? Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
[StringLength(32)]
public string IdCardNumber { get; set; }
}
}
3.1.2 有关 course
的传输对象
CourseDto
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.Courses
{
public class CourseDto
{
/// <summary>
/// 课程编号
/// </summary>
public string Number { get; set; }
/// <summary>
/// 课程名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 课程学分
/// </summary>
public int Credit { get; set; }
/// <summary>
/// 备注
/// </summary>
public string remark { get; set; }
}
}
CreateCourseDto
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MyTest.Courses
{
public class CreateCourseDto
{
/// <summary>
/// 课程编号
/// </summary>
[Required]
[StringLength(32)]
public string Number { get; set; }
/// <summary>
/// 课程名称
/// </summary>
[Required]
[StringLength(32)]
public string Name { get; set; }
/// <summary>
/// 课程学分
/// </summary>
[StringLength(8)]
public int Credit { get; set; }
/// <summary>
/// 备注
/// </summary>
[StringLength(200)]
public string remark { get; set; }
/// <summary>
/// 学生Id
/// </summary>
public List<long> StudentIds { get; set; } = new List<long>();
}
}
UpdateCourseDto
using Abp.Domain.Entities;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MyTest.Courses
{
public class UpdateCourseDto : Entity<long>
{
/// <summary>
/// 课程编号
/// </summary>
[Required]
[StringLength(32)]
public string Number { get; set; }
/// <summary>
/// 课程名称
/// </summary>
[Required]
[StringLength(32)]
public string Name { get; set; }
/// <summary>
/// 课程学分
/// </summary>
[StringLength(8)]
public int Credit { get; set; }
/// <summary>
/// 备注
/// </summary>
[StringLength(200)]
public string remark { get; set; }
/// <summary>
/// 学生Id
/// </summary>
public List<long> StudentIds { get; set; } = new List<long>();
}
}
3.1.3 有关 SC
的传输对象
StudentCourseRelatioshipDto
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyTest.StudentCourseRelationships.Dto
{
public class StudentCourseRelationshipDto
{
/// <summary>
/// 学生学号
/// </summary>
public long StudentId { get; set; }
/// <summary>
/// 课程号
/// </summary>
public long CourseId { get; set; }
/// <summary>
/// 课程成绩
/// </summary>
public int? Grade { get; set; }
}
}
CreateStudentCourseRelationshipDto
using System.ComponentModel.DataAnnotations;
namespace MyTest.StudentCourseRelationships.Dto
{
public class CreateStudentCourseRelationshipDto
{
/// <summary>
/// 学生学号
/// </summary>
[Required]
public long StudentId { get; set; }
/// <summary>
/// 课程号
/// </summary>
[Required]
public long CourseId { get; set; }
/// <summary>
/// 课程成绩
/// </summary>
public int? Grade { get; set; }
}
}
UpdateStudentCourseRelationshipDto
using Abp.Domain.Entities;
using System.ComponentModel.DataAnnotations;
namespace MyTest.StudentCourseRelationships.Dto
{
public class UpdateStudentCourseRelaionshipDto : Entity<long>
{
/// <summary>
/// 学生学号
/// </summary>
[Required]
public long StudentId { get; set; }
/// <summary>
/// 课程号
/// </summary>
public long CourseId { get; set; }
/// <summary>
/// 课程成绩
/// </summary>
[Required]
public int? Grade { get; set; }
}
}
3.2 创建应用服务接口
3.2.1 创建 student
应用服务接口
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using MyTest.Students.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyTest.Students
{
public interface IStudentAppService : IApplicationService
{
public Task<StudentDto> CreateStudentAsync(CreateStudentDto input);
public Task<int> DeleteStudentAsync(IEnumerable<long> ids);
public Task<StudentDto> UpdateStudentAsync(UpdateStudentDto input);
public Task<StudentDto> GetStudentByIdAsync(long id);
public Task<ListResultDto<StudentDto>> GetStudents();
}
}
3.2.2 创建 course
应用服务接口
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyTest.Courses
{
public interface ICourseAppService : IApplicationService
{
public Task<CourseDto> CreateCourseAsync(CreateCourseDto input);
public Task<int> DeleteCourseAsync(IEnumerable<long> ids);
public Task<CourseDto> UpdateCourseAsync(UpdateCourseDto input);
public Task<ListResultDto<CourseDto>> GetCourses();
public Task<CourseDto> GetCourseById(long id);
}
}
3.2.2 创建 sc
应用服务接口
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using MyTest.StudentCourseRelationships.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyTest.StudentCourseRelationships
{
public interface IStudentCourseRelationshipAppService : IApplicationService
{
public Task<StudentCourseRelationshipDto> CreateStudentCourseRelationshipAsync(CreateStudentCourseRelationshipDto input);
public Task<int> DeleteStudentCourseRelationshipAsync(IEnumerable<long> ids);
public Task<StudentCourseRelationshipDto> UpdateStudentCourseRelationshipAsync(UpdateStudentCourseRelaionshipDto input);
public Task<StudentCourseRelationshipDto> GetStudentCourseRelationshipByIdAsync(long id);
public Task<ListResultDto<StudentCourseRelationshipDto>> GetAllStudentCourseRelationshipsAsync();
}
}
3.3 创建应用服务
3.3.1 创建 student
应用服务
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.UI;
using MyTest.Students.Dto;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyTest.Students
{
public class StudentAppService : ApplicationService, IStudentAppService
{
private readonly IRepository<Student, long> _studentRepository;
public StudentAppService(IRepository<Student, long> studentRepository)
{
_studentRepository = studentRepository;
}
public async Task<StudentDto> CreateStudentAsync(CreateStudentDto input)
{
Student student = ObjectMapper.Map<Student>(input);
await _studentRepository.InsertAsync(student);
//await CurrentUnitOfWork.SaveChangesAsync();
StudentDto output = ObjectMapper.Map<StudentDto>(student);
return await Task.FromResult(output);
}
public async Task<int> DeleteStudentAsync(IEnumerable<long> ids)
{
int num = 0;
// 只删除存在的id
IEnumerable<long> ExistIds = _studentRepository
.GetAll()
.Where(x => ids.Contains(x.Id))
.Select(x => x.Id).ToList();
foreach (long id in ExistIds)
{
num++;
await _studentRepository.DeleteAsync(id);
}
return await Task.FromResult(num);
}
public async Task<StudentDto> GetStudentByIdAsync(long id)
{
Student student = await _studentRepository.GetAsync(id);
StudentDto result = ObjectMapper.Map<StudentDto>(student);
return await Task.FromResult(result);
}
public async Task<ListResultDto<StudentDto>> GetStudents()
{
var students = await _studentRepository.GetAllListAsync();
return new ListResultDto<StudentDto>(ObjectMapper.Map<List<StudentDto>>(students));
}
public async Task<StudentDto> UpdateStudentAsync(UpdateStudentDto input)
{
Student student = _studentRepository.FirstOrDefault(x => x.Id == input.Id);
if (student == null) throw new UserFriendlyException("该学生不存在");
ObjectMapper.Map(input, student);
Student result = await _studentRepository.UpdateAsync(student);
StudentDto output = ObjectMapper.Map<StudentDto>(result);
return await Task.FromResult(output);
}
}
3.3.2 创建 course
应用服务
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using MyTest.StudentCourseRelationships;
using MyTest.Students;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyTest.Courses
{
public class CourseAppService : ApplicationService, ICourseAppService
{
private readonly IRepository<Course, long> _courseRepository;
private readonly IRepository<StudentCourseRelationship, long> _SCRepository;
private readonly IRepository<Student, long> _studentRepository;
public CourseAppService(
IRepository<Student, long> studentRepository,
IRepository<StudentCourseRelationship, long> SCRepository,
IRepository<Course, long> courseRepository)
{
_courseRepository = courseRepository;
_SCRepository = SCRepository;
_studentRepository = studentRepository;
}
public async Task<CourseDto> CreateCourseAsync(CreateCourseDto input)
{
Course course = ObjectMapper.Map<Course>(input);
await _courseRepository.InsertAsync(course);
await CurrentUnitOfWork.SaveChangesAsync();
var studentIds = await _studentRepository
.GetAll()
.Where(x => input.StudentIds.Contains(x.Id))
.Select(x => x.Id).ToListAsync();
foreach (long studentId in studentIds)
{
var studentCourseRelationship = new StudentCourseRelationship { CourseId = course.Id, StudentId = studentId };
_SCRepository.Insert(studentCourseRelationship);
}
return await Task.FromResult(ObjectMapper.Map<CourseDto>(course));
}
public async Task<int> DeleteCourseAsync(IEnumerable<long> ids)
{
int num = 0;
// 选出Course表中存在的Id进行删除
var existIds = await _courseRepository
.GetAll()
.Where(x => ids.Contains(x.Id))
.Select(x => x.Id)
.ToListAsync();
// 判断该课程是否有学生,有则不能删除
var hasStudentIds = await _SCRepository
.GetAll()
.Where(x => existIds.Contains(x.CourseId))
.Select(x => x.Id)
.Distinct()
.ToListAsync();
existIds = existIds.Except(hasStudentIds).ToList();
foreach (var existId in existIds)
{
await _courseRepository.DeleteAsync(existId);
num++;
}
return await Task.FromResult(num);
}
public async Task<CourseDto> GetCourseById(long id)
{
Course course = _courseRepository.FirstOrDefault(id);
if (course == null) throw new UserFriendlyException("该课程不存在");
return await Task.FromResult(ObjectMapper.Map<CourseDto>(course));
}
public async Task<ListResultDto<CourseDto>> GetCourses()
{
var courses = await _courseRepository.GetAllListAsync();
return new ListResultDto<CourseDto>(ObjectMapper.Map<List<CourseDto>>(courses));
}
public async Task<CourseDto> UpdateCourseAsync(UpdateCourseDto input)
{
Course course = await _courseRepository.FirstOrDefaultAsync(input.Id);
if (course == null) throw new UserFriendlyException("不存在该课程,请先创建!");
ObjectMapper.Map(input, course);
await _courseRepository.UpdateAsync(course);
await CurrentUnitOfWork.SaveChangesAsync();
// 该课程原先关联的学生
var originStudentIds = await _SCRepository
.GetAll()
.Where(x => x.CourseId == input.Id)
.Select(x => x.StudentId).ToListAsync();
// 需要删除的
var deleteStudentIds = originStudentIds.Except(input.StudentIds);
// 需要新增的
var newStudentIds = input.StudentIds.Except(originStudentIds);
// 检查新增学生是否存在
newStudentIds = await _studentRepository
.GetAll()
.Where(x => newStudentIds.Contains(x.Id))
.Select(x => x.Id)
.ToListAsync();
// 删除
foreach (var deleteStudentId in deleteStudentIds)
{
var studentCourseRelationship = course.SC.FirstOrDefault(x => x.StudentId == deleteStudentId);
if (studentCourseRelationship != null) course.SC.Remove(studentCourseRelationship);
}
// 增加
foreach (var newStudentId in newStudentIds)
{
course.SC.Add(new StudentCourseRelationship { CourseId = input.Id, StudentId = newStudentId });
}
await _courseRepository.UpdateAsync(course);
return await Task.FromResult(ObjectMapper.Map<CourseDto>(course));
}
}
}
3.3.3 创建 SC
应用服务
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using MyTest.Courses;
using MyTest.StudentCourseRelationships.Dto;
using MyTest.Students;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyTest.StudentCourseRelationships
{
public class StudentCourseRelationshipAppService : ApplicationService, IStudentCourseRelationshipAppService
{
private readonly IRepository<StudentCourseRelationship, long> _SCRepository;
private readonly IRepository<Student, long> _studentRepository;
private readonly IRepository<Course, long> _courseRepository;
public StudentCourseRelationshipAppService(
IRepository<Course, long> courseRepository,
IRepository<Student, long> studentRepository,
IRepository<StudentCourseRelationship, long> SCRepository)
{
_SCRepository = SCRepository;
_courseRepository = courseRepository;
_studentRepository = studentRepository;
}
public async Task<StudentCourseRelationshipDto> CreateStudentCourseRelationshipAsync(CreateStudentCourseRelationshipDto input)
{
var entity = ObjectMapper.Map<StudentCourseRelationship>(input);
// 检查是否存在该id的学生
bool isStudentExists = await _studentRepository
.GetAll()
.Where(x => x.Id == input.StudentId)
.AnyAsync();
// 检查是否存在该id的课程
bool isCourseExists = await _courseRepository
.GetAll()
.Where(x => x.Id == input.CourseId)
.AnyAsync();
if (!isStudentExists) throw new UserFriendlyException("该学生不存在,请先创建~");
if (!isCourseExists) throw new UserFriendlyException("该课程不存在,请先创建~");
await _SCRepository.InsertAsync(entity);
return await Task.FromResult(ObjectMapper.Map<StudentCourseRelationshipDto>(entity));
}
public async Task<int> DeleteStudentCourseRelationshipAsync(IEnumerable<long> ids)
{
// 检查要删除的id是否存在
var deleteIds = await _SCRepository
.GetAll()
.Where(x => ids.Contains(x.Id))
.Select(x => x.Id)
.ToListAsync();
int num = 0;
foreach (long deleteId in deleteIds)
{
await _SCRepository.DeleteAsync(deleteId);
num++;
}
return await Task.FromResult(num);
}
public async Task<ListResultDto<StudentCourseRelationshipDto>> GetAllStudentCourseRelationshipsAsync()
{
var results = await _SCRepository.GetAllListAsync();
return new ListResultDto<StudentCourseRelationshipDto>(ObjectMapper.Map<List<StudentCourseRelationshipDto>>(results));
}
public async Task<StudentCourseRelationshipDto> GetStudentCourseRelationshipByIdAsync(long id)
{
var entity = await _SCRepository.FirstOrDefaultAsync(id);
if (entity == null) throw new UserFriendlyException("该id不存在学生课程关系");
return await Task.FromResult(ObjectMapper.Map<StudentCourseRelationshipDto>(entity));
}
public async Task<StudentCourseRelationshipDto> UpdateStudentCourseRelationshipAsync(UpdateStudentCourseRelaionshipDto input)
{
var entity = await _SCRepository.FirstOrDefaultAsync(input.Id);
if (entity == null) throw new UserFriendlyException("你要更新的学生不存在");
ObjectMapper.Map(input, entity);
bool isStudentExists = await _studentRepository
.GetAll()
.Where(x => x.Id == input.StudentId)
.AnyAsync();
bool isCourseExists = await _courseRepository
.GetAll()
.Where(x => x.Id == input.CourseId)
.AnyAsync();
if (!isStudentExists) throw new UserFriendlyException("该学生不存在,请先创建~");
if (!isCourseExists) throw new UserFriendlyException("该课程不存在,请先创建~");
await _SCRepository.UpdateAsync(entity);
return await Task.FromResult(ObjectMapper.Map<StudentCourseRelationshipDto>(entity));
}
}
}
3.4 创建映射文件
3.4.1 创建 student
映射文件
using AutoMapper;
using MyTest.Students.Dto;
namespace MyTest.Students
{
public class StudentMapProfile : Profile
{
public StudentMapProfile()
{
CreateMap<Student, StudentDto>().ReverseMap();
CreateMap<CreateStudentDto, Student>();
CreateMap<UpdateStudentDto, Student>();
}
}
}
3.4.2 创建 course
映射文件
using AutoMapper;
namespace MyTest.Courses
{
public class CourseMapProfile : Profile
{
public CourseMapProfile()
{
CreateMap<Course, CourseDto>().ReverseMap();
CreateMap<UpdateCourseDto, Course>();
CreateMap<CreateCourseDto, Course>();
}
}
}
3.4.3 创建 studentcourserelationship
映射文件
using AutoMapper;
using MyTest.StudentCourseRelationships.Dto;
namespace MyTest.StudentCourseRelationships
{
public class StudentCourseRelationshipMapProfile : Profile
{
public StudentCourseRelationshipMapProfile()
{
CreateMap<StudentCourseRelationshipDto, StudentCourseRelationship>().ReverseMap();
CreateMap<CreateStudentCourseRelationshipDto, StudentCourseRelationship>();
CreateMap<UpdateStudentCourseRelaionshipDto, StudentCourseRelationship>();
}
}
}
4. 启动项目
看到有一下接口,可以测试一下,看看是否达到预期效果。
本文作者:岁月飞扬
本文链接:https://www.cnblogs.com/jerry-1015/p/16539732.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步