This commit is contained in:
2026-07-24 12:42:51 +08:00 Unverified
commit 67905dfa16
56 changed files with 7630 additions and 0 deletions
@@ -0,0 +1,90 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Route("api/auth")]
public sealed class AuthController(
UserManager<ApplicationUser> userManager,
ITokenService tokenService) : ControllerBase
{
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<LoginResponse>> Login(LoginRequest request)
{
var user = await userManager.FindByNameAsync(request.UserName);
if (user is null || !user.IsEnabled)
{
return Unauthorized(new ProblemDetails
{
Title = "登录失败",
Detail = "账号或密码不正确,或账号已停用。",
Status = StatusCodes.Status401Unauthorized
});
}
if (await userManager.IsLockedOutAsync(user) ||
!await userManager.CheckPasswordAsync(user, request.Password))
{
await userManager.AccessFailedAsync(user);
return Unauthorized(new ProblemDetails
{
Title = "登录失败",
Detail = "账号或密码不正确,或账号已停用。",
Status = StatusCodes.Status401Unauthorized
});
}
await userManager.ResetAccessFailedCountAsync(user);
user.LastLoginAt = DateTime.UtcNow;
await userManager.UpdateAsync(user);
var roles = await userManager.GetRolesAsync(user);
return new LoginResponse(
tokenService.Create(user, roles),
new CurrentUserResponse(
user.Id,
user.UserName!,
user.DisplayName,
roles,
user.CollegeId));
}
[Authorize]
[HttpGet("me")]
public async Task<ActionResult<CurrentUserResponse>> Me()
{
var id = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = id is null ? null : await userManager.FindByIdAsync(id);
if (user is null || !user.IsEnabled)
{
return Unauthorized();
}
return new CurrentUserResponse(
user.Id,
user.UserName!,
user.DisplayName,
await userManager.GetRolesAsync(user),
user.CollegeId);
}
}
public sealed record LoginRequest(
[Required, MaxLength(100)] string UserName,
[Required, MaxLength(100)] string Password);
public sealed record LoginResponse(string Token, CurrentUserResponse User);
public sealed record CurrentUserResponse(
Guid Id,
string UserName,
string DisplayName,
IEnumerable<string> Roles,
Guid? CollegeId);
@@ -0,0 +1,468 @@
using System.ComponentModel.DataAnnotations;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Common;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/base-data")]
public sealed class BaseDataController(AppDbContext db) : ControllerBase
{
private const string Administrators =
$"{SystemRoles.SuperAdmin},{SystemRoles.AcademicAdmin}";
[HttpGet("campuses")]
public async Task<ActionResult<IReadOnlyCollection<Campus>>> GetCampuses(
CancellationToken cancellationToken) =>
await db.Campuses.AsNoTracking()
.OrderBy(x => x.SortOrder).ThenBy(x => x.Code)
.ToListAsync(cancellationToken);
[HttpPost("campuses")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Campus>> CreateCampus(
CatalogRequest request,
CancellationToken cancellationToken)
{
var entity = new Campus
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
Address = request.Description?.Trim(),
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetCampuses", cancellationToken);
}
[HttpPut("campuses/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Campus>> UpdateCampus(
Guid id,
CatalogRequest request,
CancellationToken cancellationToken)
{
var entity = await db.Campuses.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
ApplyCatalog(entity, request);
entity.Address = request.Description?.Trim();
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpGet("colleges")]
public async Task<ActionResult<object>> GetColleges(CancellationToken cancellationToken) =>
Ok(await db.Colleges.AsNoTracking()
.OrderBy(x => x.SortOrder).ThenBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.ShortName, x.CampusId,
CampusName = x.Campus != null ? x.Campus.Name : null,
x.IsEnabled, x.SortOrder
})
.ToListAsync(cancellationToken));
[HttpPost("colleges")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<College>> CreateCollege(
CollegeRequest request,
CancellationToken cancellationToken)
{
if (request.CampusId.HasValue &&
!await db.Campuses.AnyAsync(x => x.Id == request.CampusId, cancellationToken))
{
return ValidationProblem("所选校区不存在。");
}
var entity = new College
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
ShortName = request.ShortName?.Trim(),
CampusId = request.CampusId,
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetColleges", cancellationToken);
}
[HttpPut("colleges/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<College>> UpdateCollege(
Guid id,
CollegeRequest request,
CancellationToken cancellationToken)
{
var entity = await db.Colleges.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
ApplyCatalog(entity, request);
entity.ShortName = request.ShortName?.Trim();
entity.CampusId = request.CampusId;
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpGet("majors")]
public async Task<ActionResult<object>> GetMajors(CancellationToken cancellationToken) =>
Ok(await db.Majors.AsNoTracking()
.OrderBy(x => x.SortOrder).ThenBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.CollegeId,
CollegeName = x.College!.Name,
x.DegreeType, x.SchoolingYears, x.IsEnabled, x.SortOrder
})
.ToListAsync(cancellationToken));
[HttpPost("majors")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Major>> CreateMajor(
MajorRequest request,
CancellationToken cancellationToken)
{
if (!await db.Colleges.AnyAsync(x => x.Id == request.CollegeId, cancellationToken))
return ValidationProblem("所选学院不存在。");
var entity = new Major
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
CollegeId = request.CollegeId,
DegreeType = request.DegreeType.Trim(),
SchoolingYears = request.SchoolingYears,
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetMajors", cancellationToken);
}
[HttpPut("majors/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Major>> UpdateMajor(
Guid id,
MajorRequest request,
CancellationToken cancellationToken)
{
var entity = await db.Majors.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
ApplyCatalog(entity, request);
entity.CollegeId = request.CollegeId;
entity.DegreeType = request.DegreeType.Trim();
entity.SchoolingYears = request.SchoolingYears;
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpGet("classes")]
public async Task<ActionResult<object>> GetClasses(CancellationToken cancellationToken) =>
Ok(await db.AdministrativeClasses.AsNoTracking()
.OrderByDescending(x => x.Grade).ThenBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.MajorId,
MajorName = x.Major!.Name,
CollegeName = x.Major.College!.Name,
x.Grade, x.CounselorName, x.IsEnabled, x.SortOrder
})
.ToListAsync(cancellationToken));
[HttpPost("classes")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<AdministrativeClass>> CreateClass(
ClassRequest request,
CancellationToken cancellationToken)
{
if (!await db.Majors.AnyAsync(x => x.Id == request.MajorId, cancellationToken))
return ValidationProblem("所选专业不存在。");
var entity = new AdministrativeClass
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
MajorId = request.MajorId,
Grade = request.Grade,
CounselorName = request.CounselorName?.Trim(),
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetClasses", cancellationToken);
}
[HttpPut("classes/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<AdministrativeClass>> UpdateClass(
Guid id,
ClassRequest request,
CancellationToken cancellationToken)
{
var entity = await db.AdministrativeClasses.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
ApplyCatalog(entity, request);
entity.MajorId = request.MajorId;
entity.Grade = request.Grade;
entity.CounselorName = request.CounselorName?.Trim();
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpGet("terms")]
public async Task<ActionResult<IReadOnlyCollection<AcademicTerm>>> GetTerms(
CancellationToken cancellationToken) =>
await db.AcademicTerms.AsNoTracking()
.OrderByDescending(x => x.StartDate)
.ToListAsync(cancellationToken);
[HttpPost("terms")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<AcademicTerm>> CreateTerm(
TermRequest request,
CancellationToken cancellationToken)
{
if (request.EndDate <= request.StartDate)
return ValidationProblem("学期结束日期必须晚于开始日期。");
if (request.IsCurrent)
await db.AcademicTerms.ExecuteUpdateAsync(
setters => setters.SetProperty(x => x.IsCurrent, false),
cancellationToken);
var entity = new AcademicTerm
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
AcademicYear = request.AcademicYear.Trim(),
Season = request.Season,
StartDate = request.StartDate,
EndDate = request.EndDate,
IsCurrent = request.IsCurrent,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetTerms", cancellationToken);
}
[HttpPut("terms/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<AcademicTerm>> UpdateTerm(
Guid id,
TermRequest request,
CancellationToken cancellationToken)
{
var entity = await db.AcademicTerms.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
if (request.IsCurrent)
await db.AcademicTerms.Where(x => x.Id != id).ExecuteUpdateAsync(
setters => setters.SetProperty(x => x.IsCurrent, false),
cancellationToken);
ApplyCatalog(entity, request);
entity.AcademicYear = request.AcademicYear.Trim();
entity.Season = request.Season;
entity.StartDate = request.StartDate;
entity.EndDate = request.EndDate;
entity.IsCurrent = request.IsCurrent;
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpGet("classrooms")]
public async Task<ActionResult<object>> GetClassrooms(CancellationToken cancellationToken) =>
Ok(await db.Classrooms.AsNoTracking()
.OrderBy(x => x.Building!.Campus!.SortOrder)
.ThenBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.BuildingId,
BuildingName = x.Building!.Name,
CampusName = x.Building.Campus!.Name,
x.Capacity, x.RoomType, x.Equipment, x.IsEnabled, x.SortOrder
})
.ToListAsync(cancellationToken));
[HttpGet("buildings")]
public async Task<ActionResult<object>> GetBuildings(CancellationToken cancellationToken) =>
Ok(await db.Buildings.AsNoTracking()
.OrderBy(x => x.SortOrder).ThenBy(x => x.Code)
.Select(x => new
{
x.Id, x.Code, x.Name, x.CampusId,
CampusName = x.Campus!.Name, x.IsEnabled, x.SortOrder
})
.ToListAsync(cancellationToken));
[HttpPost("buildings")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Building>> CreateBuilding(
BuildingRequest request,
CancellationToken cancellationToken)
{
if (!await db.Campuses.AnyAsync(x => x.Id == request.CampusId, cancellationToken))
return ValidationProblem("所选校区不存在。");
var entity = new Building
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
CampusId = request.CampusId,
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetBuildings", cancellationToken);
}
[HttpPost("classrooms")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Classroom>> CreateClassroom(
ClassroomRequest request,
CancellationToken cancellationToken)
{
if (!await db.Buildings.AnyAsync(x => x.Id == request.BuildingId, cancellationToken))
return ValidationProblem("所选教学楼不存在。");
var entity = new Classroom
{
Code = request.Code.Trim(),
Name = request.Name.Trim(),
BuildingId = request.BuildingId,
Capacity = request.Capacity,
RoomType = request.RoomType.Trim(),
Equipment = request.Equipment?.Trim(),
SortOrder = request.SortOrder,
IsEnabled = request.IsEnabled
};
return await CreateAsync(entity, "GetClassrooms", cancellationToken);
}
[HttpPut("classrooms/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<ActionResult<Classroom>> UpdateClassroom(
Guid id,
ClassroomRequest request,
CancellationToken cancellationToken)
{
var entity = await db.Classrooms.FindAsync([id], cancellationToken);
if (entity is null) return NotFound();
ApplyCatalog(entity, request);
entity.BuildingId = request.BuildingId;
entity.Capacity = request.Capacity;
entity.RoomType = request.RoomType.Trim();
entity.Equipment = request.Equipment?.Trim();
await db.SaveChangesAsync(cancellationToken);
return entity;
}
[HttpDelete("{kind}/{id:guid}")]
[Authorize(Roles = Administrators)]
public async Task<IActionResult> Delete(
string kind,
Guid id,
CancellationToken cancellationToken)
{
object? entity = kind.ToLowerInvariant() switch
{
"campuses" => await db.Campuses.FindAsync([id], cancellationToken),
"colleges" => await db.Colleges.FindAsync([id], cancellationToken),
"majors" => await db.Majors.FindAsync([id], cancellationToken),
"classes" => await db.AdministrativeClasses.FindAsync([id], cancellationToken),
"terms" => await db.AcademicTerms.FindAsync([id], cancellationToken),
"buildings" => await db.Buildings.FindAsync([id], cancellationToken),
"classrooms" => await db.Classrooms.FindAsync([id], cancellationToken),
_ => null
};
if (entity is null) return NotFound();
db.Remove(entity);
try
{
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
catch (DbUpdateException)
{
return Conflict(new ProblemDetails
{
Title = "无法删除",
Detail = "该数据已被其他业务引用,请先停用,或移除关联数据后再删除。",
Status = StatusCodes.Status409Conflict
});
}
}
private async Task<ActionResult<TEntity>> CreateAsync<TEntity>(
TEntity entity,
string action,
CancellationToken cancellationToken)
where TEntity : EntityBase
{
db.Add(entity);
try
{
await db.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException)
{
ModelState.AddModelError("code", "编码已存在或关联数据无效。");
return ValidationProblem(ModelState);
}
return CreatedAtAction(action, new { id = entity.Id }, entity);
}
private static void ApplyCatalog(CatalogEntity entity, CatalogRequest request)
{
entity.Code = request.Code.Trim();
entity.Name = request.Name.Trim();
entity.SortOrder = request.SortOrder;
entity.IsEnabled = request.IsEnabled;
}
}
public record CatalogRequest(
[Required, MaxLength(40)] string Code,
[Required, MaxLength(100)] string Name,
int SortOrder = 0,
bool IsEnabled = true,
[MaxLength(300)] string? Description = null);
public sealed record CollegeRequest(
string Code, string Name, int SortOrder, bool IsEnabled,
Guid? CampusId,
[MaxLength(50)] string? ShortName)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
public sealed record MajorRequest(
string Code, string Name, int SortOrder, bool IsEnabled,
Guid CollegeId,
[Required, MaxLength(30)] string DegreeType,
[Range(1, 8)] int SchoolingYears)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
public sealed record ClassRequest(
string Code, string Name, int SortOrder, bool IsEnabled,
Guid MajorId,
[Range(2000, 2200)] int Grade,
[MaxLength(50)] string? CounselorName)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
public sealed record TermRequest(
string Code, string Name, bool IsEnabled,
[Required, MaxLength(20)] string AcademicYear,
TermSeason Season,
DateOnly StartDate,
DateOnly EndDate,
bool IsCurrent)
: CatalogRequest(Code, Name, 0, IsEnabled);
public sealed record BuildingRequest(
string Code, string Name, int SortOrder, bool IsEnabled,
Guid CampusId)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
public sealed record ClassroomRequest(
string Code, string Name, int SortOrder, bool IsEnabled,
Guid BuildingId,
[Range(1, 1000)] int Capacity,
[Required, MaxLength(40)] string RoomType,
[MaxLength(300)] string? Equipment)
: CatalogRequest(Code, Name, SortOrder, IsEnabled);
@@ -0,0 +1,36 @@
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/dashboard")]
public sealed class DashboardController(AppDbContext db) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<object>> Get(CancellationToken cancellationToken)
{
var currentTerm = await db.AcademicTerms
.AsNoTracking()
.Where(x => x.IsCurrent)
.Select(x => new { x.Id, x.Name, x.StartDate, x.EndDate })
.FirstOrDefaultAsync(cancellationToken);
return new
{
CurrentTerm = currentTerm,
Counts = new
{
Campuses = await db.Campuses.CountAsync(cancellationToken),
Colleges = await db.Colleges.CountAsync(cancellationToken),
Majors = await db.Majors.CountAsync(cancellationToken),
Classes = await db.AdministrativeClasses.CountAsync(cancellationToken),
Classrooms = await db.Classrooms.CountAsync(cancellationToken),
Users = await db.Users.CountAsync(cancellationToken)
}
};
}
}
@@ -0,0 +1,143 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Jiaowu.Api.Domain.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Controllers;
[ApiController]
[Authorize(Roles = SystemRoles.SuperAdmin)]
[Route("api/users")]
public sealed class UsersController(
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<object>> GetUsers(CancellationToken cancellationToken)
{
var users = await userManager.Users.AsNoTracking()
.OrderBy(x => x.UserName)
.Select(x => new
{
x.Id, x.UserName, x.DisplayName, x.StaffNumber,
x.CollegeId, x.IsEnabled, x.LastLoginAt, x.CreatedAt
})
.ToListAsync(cancellationToken);
var result = new List<object>();
foreach (var user in users)
{
var identityUser = await userManager.FindByIdAsync(user.Id.ToString());
result.Add(new
{
user.Id, user.UserName, user.DisplayName, user.StaffNumber,
user.CollegeId, user.IsEnabled, user.LastLoginAt, user.CreatedAt,
Roles = identityUser is null
? []
: await userManager.GetRolesAsync(identityUser)
});
}
return Ok(result);
}
[HttpGet("roles")]
public async Task<ActionResult<object>> GetRoles(CancellationToken cancellationToken) =>
Ok(await roleManager.Roles.AsNoTracking()
.OrderBy(x => x.Name)
.Select(x => new { x.Name, x.Description, x.DataScope })
.ToListAsync(cancellationToken));
[HttpPost]
public async Task<ActionResult> Create(CreateUserRequest request)
{
var invalidRoles = request.Roles
.Except(SystemRoles.All, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (invalidRoles.Length > 0)
return ValidationProblem($"无效角色:{string.Join("", invalidRoles)}");
var user = new ApplicationUser
{
UserName = request.UserName.Trim(),
DisplayName = request.DisplayName.Trim(),
StaffNumber = request.StaffNumber?.Trim(),
CollegeId = request.CollegeId,
LockoutEnabled = true,
IsEnabled = true
};
var result = await userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
return IdentityValidationProblem(result);
result = await userManager.AddToRolesAsync(user, request.Roles);
if (!result.Succeeded)
return IdentityValidationProblem(result);
return CreatedAtAction(nameof(GetUsers), new { id = user.Id }, new { user.Id });
}
[HttpPut("{id:guid}/status")]
public async Task<IActionResult> SetStatus(Guid id, SetUserStatusRequest request)
{
var user = await userManager.FindByIdAsync(id.ToString());
if (user is null) return NotFound();
if (User.FindFirstValue(ClaimTypes.NameIdentifier) == id.ToString() &&
!request.IsEnabled)
return ValidationProblem("不能停用当前登录账号。");
user.IsEnabled = request.IsEnabled;
var result = await userManager.UpdateAsync(user);
return result.Succeeded ? NoContent() : IdentityValidationProblem(result);
}
[HttpPut("{id:guid}/roles")]
public async Task<IActionResult> SetRoles(Guid id, SetRolesRequest request)
{
var user = await userManager.FindByIdAsync(id.ToString());
if (user is null) return NotFound();
var invalidRoles = request.Roles
.Except(SystemRoles.All, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (invalidRoles.Length > 0)
return ValidationProblem($"无效角色:{string.Join("", invalidRoles)}");
var existing = await userManager.GetRolesAsync(user);
if (User.FindFirstValue(ClaimTypes.NameIdentifier) == id.ToString() &&
existing.Contains(SystemRoles.SuperAdmin) &&
!request.Roles.Contains(SystemRoles.SuperAdmin))
{
return ValidationProblem("不能移除当前账号的超级管理员角色。");
}
var removeResult = await userManager.RemoveFromRolesAsync(
user,
existing.Except(request.Roles));
if (!removeResult.Succeeded) return IdentityValidationProblem(removeResult);
var addResult = await userManager.AddToRolesAsync(
user,
request.Roles.Except(existing));
return addResult.Succeeded ? NoContent() : IdentityValidationProblem(addResult);
}
private ActionResult IdentityValidationProblem(IdentityResult result)
{
foreach (var error in result.Errors)
ModelState.AddModelError(error.Code, error.Description);
return ValidationProblem(ModelState);
}
}
public sealed record CreateUserRequest(
[Required, MaxLength(50)] string UserName,
[Required, MaxLength(50)] string DisplayName,
[Required, MinLength(8), MaxLength(100)] string Password,
[MaxLength(30)] string? StaffNumber,
Guid? CollegeId,
[MinLength(1)] string[] Roles);
public sealed record SetUserStatusRequest(bool IsEnabled);
public sealed record SetRolesRequest([MinLength(1)] string[] Roles);
@@ -0,0 +1,62 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.Academic;
public sealed class Campus : CatalogEntity
{
public string? Address { get; set; }
}
public sealed class College : CatalogEntity
{
public Guid? CampusId { get; set; }
public Campus? Campus { get; set; }
public string? ShortName { get; set; }
}
public sealed class Major : CatalogEntity
{
public Guid CollegeId { get; set; }
public College? College { get; set; }
public required string DegreeType { get; set; }
public int SchoolingYears { get; set; } = 4;
}
public sealed class AdministrativeClass : CatalogEntity
{
public Guid MajorId { get; set; }
public Major? Major { get; set; }
public int Grade { get; set; }
public string? CounselorName { get; set; }
}
public sealed class Building : CatalogEntity
{
public Guid CampusId { get; set; }
public Campus? Campus { get; set; }
}
public sealed class Classroom : CatalogEntity
{
public Guid BuildingId { get; set; }
public Building? Building { get; set; }
public int Capacity { get; set; }
public string RoomType { get; set; } = "普通教室";
public string? Equipment { get; set; }
}
public sealed class AcademicTerm : CatalogEntity
{
public required string AcademicYear { get; set; }
public TermSeason Season { get; set; }
public DateOnly StartDate { get; set; }
public DateOnly EndDate { get; set; }
public bool IsCurrent { get; set; }
}
public enum TermSeason
{
Autumn = 1,
Spring = 2,
Summer = 3
}
@@ -0,0 +1,16 @@
namespace Jiaowu.Api.Domain.Common;
public abstract class EntityBase
{
public Guid Id { get; set; } = Guid.NewGuid();
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
public abstract class CatalogEntity : EntityBase
{
public required string Code { get; set; }
public required string Name { get; set; }
public int SortOrder { get; set; }
public bool IsEnabled { get; set; } = true;
}
@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Identity;
namespace Jiaowu.Api.Domain.Identity;
public sealed class ApplicationUser : IdentityUser<Guid>
{
public required string DisplayName { get; set; }
public string? StaffNumber { get; set; }
public Guid? CollegeId { get; set; }
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime? LastLoginAt { get; set; }
}
public sealed class ApplicationRole : IdentityRole<Guid>
{
public string? Description { get; set; }
public DataScope DataScope { get; set; } = DataScope.Self;
}
public enum DataScope
{
Self = 0,
Class = 1,
College = 2,
All = 3
}
public static class SystemRoles
{
public const string SuperAdmin = "SuperAdmin";
public const string AcademicAdmin = "AcademicAdmin";
public const string CollegeAdmin = "CollegeAdmin";
public const string Teacher = "Teacher";
public const string Counselor = "Counselor";
public const string Student = "Student";
public const string Leader = "Leader";
public static readonly string[] All =
[
SuperAdmin,
AcademicAdmin,
CollegeAdmin,
Teacher,
Counselor,
Student,
Leader
];
}
+13
View File
@@ -0,0 +1,13 @@
using Jiaowu.Api.Domain.Common;
namespace Jiaowu.Api.Domain.System;
public sealed class AuditLog : EntityBase
{
public Guid? UserId { get; set; }
public string? UserName { get; set; }
public required string Method { get; set; }
public required string Path { get; set; }
public int StatusCode { get; set; }
public string? IpAddress { get; set; }
}
@@ -0,0 +1,10 @@
namespace Jiaowu.Api.Infrastructure.Auth;
public sealed class JwtOptions
{
public const string SectionName = "Jwt";
public string Issuer { get; set; } = "Jiaowu.Api";
public string Audience { get; set; } = "Jiaowu.Web";
public string Key { get; set; } = string.Empty;
public int ExpireMinutes { get; set; } = 480;
}
@@ -0,0 +1,48 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Jiaowu.Api.Domain.Identity;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Jiaowu.Api.Infrastructure.Auth;
public interface ITokenService
{
string Create(ApplicationUser user, IEnumerable<string> roles);
}
public sealed class TokenService(IOptions<JwtOptions> options) : ITokenService
{
private readonly JwtOptions _options = options.Value;
public string Create(ApplicationUser user, IEnumerable<string> roles)
{
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.UniqueName, user.UserName ?? string.Empty),
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Name, user.DisplayName)
};
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
if (user.CollegeId is { } collegeId)
{
claims.Add(new Claim("college_id", collegeId.ToString()));
}
var credentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key)),
SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_options.ExpireMinutes),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
@@ -0,0 +1,38 @@
using System.Security.Claims;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Persistence;
namespace Jiaowu.Api.Infrastructure.Middleware;
public sealed class AuditMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
await next(context);
if (HttpMethods.IsGet(context.Request.Method) ||
context.Request.Path.StartsWithSegments("/swagger"))
{
return;
}
// A failed business write can leave invalid tracked entities in this request scope.
// Audit persistence must not retry those entities and replace the original response.
db.ChangeTracker.Clear();
db.AuditLogs.Add(new AuditLog
{
UserId = Guid.TryParse(
context.User.FindFirstValue(ClaimTypes.NameIdentifier),
out var userId)
? userId
: null,
UserName = context.User.Identity?.Name,
Method = context.Request.Method,
Path = context.Request.Path,
StatusCode = context.Response.StatusCode,
IpAddress = context.Connection.RemoteIpAddress?.ToString()
});
await db.SaveChangesAsync(context.RequestAborted);
}
}
@@ -0,0 +1,111 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Common;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Infrastructure.Persistence;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: IdentityDbContext<ApplicationUser, ApplicationRole, Guid>(options)
{
public DbSet<Campus> Campuses => Set<Campus>();
public DbSet<College> Colleges => Set<College>();
public DbSet<Major> Majors => Set<Major>();
public DbSet<AdministrativeClass> AdministrativeClasses => Set<AdministrativeClass>();
public DbSet<Building> Buildings => Set<Building>();
public DbSet<Classroom> Classrooms => Set<Classroom>();
public DbSet<AcademicTerm> AcademicTerms => Set<AcademicTerm>();
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(entity =>
{
entity.Property(x => x.DisplayName).HasMaxLength(50);
entity.Property(x => x.StaffNumber).HasMaxLength(30);
entity.HasIndex(x => x.StaffNumber);
});
builder.Entity<ApplicationRole>(entity =>
{
entity.Property(x => x.Description).HasMaxLength(100);
});
ConfigureCatalog<Campus>(builder);
ConfigureCatalog<College>(builder);
ConfigureCatalog<Major>(builder);
ConfigureCatalog<AdministrativeClass>(builder);
ConfigureCatalog<Building>(builder);
ConfigureCatalog<Classroom>(builder);
ConfigureCatalog<AcademicTerm>(builder);
builder.Entity<College>()
.HasOne(x => x.Campus)
.WithMany()
.HasForeignKey(x => x.CampusId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<Major>()
.HasOne(x => x.College)
.WithMany()
.HasForeignKey(x => x.CollegeId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<AdministrativeClass>()
.HasOne(x => x.Major)
.WithMany()
.HasForeignKey(x => x.MajorId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<Building>()
.HasOne(x => x.Campus)
.WithMany()
.HasForeignKey(x => x.CampusId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<Classroom>()
.HasOne(x => x.Building)
.WithMany()
.HasForeignKey(x => x.BuildingId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<AcademicTerm>()
.HasIndex(x => x.IsCurrent);
builder.Entity<AuditLog>(entity =>
{
entity.Property(x => x.Method).HasMaxLength(10);
entity.Property(x => x.Path).HasMaxLength(300);
entity.Property(x => x.UserName).HasMaxLength(100);
entity.Property(x => x.IpAddress).HasMaxLength(64);
entity.HasIndex(x => x.CreatedAt);
});
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
foreach (var entry in ChangeTracker.Entries<EntityBase>()
.Where(x => x.State == EntityState.Modified))
{
entry.Entity.UpdatedAt = DateTime.UtcNow;
}
return base.SaveChangesAsync(cancellationToken);
}
private static void ConfigureCatalog<TEntity>(ModelBuilder builder)
where TEntity : CatalogEntity
{
builder.Entity<TEntity>(entity =>
{
entity.Property(x => x.Code).HasMaxLength(40);
entity.Property(x => x.Name).HasMaxLength(100);
entity.HasIndex(x => x.Code).IsUnique();
entity.HasIndex(x => new { x.IsEnabled, x.SortOrder });
});
}
}
@@ -0,0 +1,190 @@
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Infrastructure.Persistence;
public sealed class DatabaseInitializer(
AppDbContext db,
RoleManager<ApplicationRole> roleManager,
UserManager<ApplicationUser> userManager,
IConfiguration configuration,
IHostEnvironment environment,
ILogger<DatabaseInitializer> logger)
{
public async Task InitializeAsync()
{
if (environment.IsDevelopment())
{
await db.Database.EnsureCreatedAsync();
}
else
{
await db.Database.MigrateAsync();
}
await SeedRolesAsync();
await SeedAdministratorAsync();
if (environment.IsDevelopment())
{
await SeedDevelopmentDataAsync();
}
}
private async Task SeedRolesAsync()
{
var roleDefinitions = new Dictionary<string, (string Description, DataScope Scope)>
{
[SystemRoles.SuperAdmin] = ("系统配置与全部数据管理", DataScope.All),
[SystemRoles.AcademicAdmin] = ("校级教务管理", DataScope.All),
[SystemRoles.CollegeAdmin] = ("院系教务管理", DataScope.College),
[SystemRoles.Teacher] = ("教师教学工作台", DataScope.Self),
[SystemRoles.Counselor] = ("辅导员与班级管理", DataScope.Class),
[SystemRoles.Student] = ("学生自助服务", DataScope.Self),
[SystemRoles.Leader] = ("校级统计查看", DataScope.All)
};
foreach (var (name, definition) in roleDefinitions)
{
if (await roleManager.RoleExistsAsync(name))
{
continue;
}
var result = await roleManager.CreateAsync(new ApplicationRole
{
Name = name,
Description = definition.Description,
DataScope = definition.Scope
});
EnsureSucceeded(result, $"创建角色 {name}");
}
}
private async Task SeedAdministratorAsync()
{
var userName = configuration["SeedAdmin:UserName"];
var password = configuration["SeedAdmin:Password"];
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
{
if (!environment.IsDevelopment())
{
logger.LogWarning("未配置 SeedAdmin,生产环境不会创建默认管理员。");
}
return;
}
var user = await userManager.FindByNameAsync(userName);
if (user is null)
{
user = new ApplicationUser
{
UserName = userName,
DisplayName = configuration["SeedAdmin:DisplayName"] ?? "系统管理员",
LockoutEnabled = true,
IsEnabled = true
};
EnsureSucceeded(await userManager.CreateAsync(user, password), "创建初始管理员");
}
if (!user.LockoutEnabled)
{
user.LockoutEnabled = true;
EnsureSucceeded(await userManager.UpdateAsync(user), "启用管理员登录保护");
}
if (!await userManager.IsInRoleAsync(user, SystemRoles.SuperAdmin))
{
EnsureSucceeded(
await userManager.AddToRoleAsync(user, SystemRoles.SuperAdmin),
"授予超级管理员角色");
}
}
private async Task SeedDevelopmentDataAsync()
{
if (await db.Campuses.AnyAsync())
{
return;
}
var campus = new Campus
{
Code = "MAIN",
Name = "主校区",
Address = "大学路 1 号"
};
var college = new College
{
Code = "CS",
Name = "计算机学院",
ShortName = "计算机学院",
CampusId = campus.Id
};
var major = new Major
{
Code = "080901",
Name = "计算机科学与技术",
CollegeId = college.Id,
DegreeType = "工学学士",
SchoolingYears = 4
};
var building = new Building
{
Code = "J1",
Name = "第一教学楼",
CampusId = campus.Id
};
db.AddRange(
campus,
college,
major,
new AdministrativeClass
{
Code = "CS2026-01",
Name = "计科 2026-1 班",
MajorId = major.Id,
Grade = 2026,
CounselorName = "陈老师"
},
building,
new Classroom
{
Code = "J1-201",
Name = "J1-201",
BuildingId = building.Id,
Capacity = 60,
RoomType = "多媒体教室",
Equipment = "投影、扩声、录播"
},
new AcademicTerm
{
Code = "2026-2027-1",
Name = "2026—2027 学年第一学期",
AcademicYear = "2026-2027",
Season = TermSeason.Autumn,
StartDate = new DateOnly(2026, 9, 7),
EndDate = new DateOnly(2027, 1, 17),
IsCurrent = true
});
await db.SaveChangesAsync();
}
private static void EnsureSucceeded(IdentityResult result, string action)
{
if (result.Succeeded)
{
return;
}
throw new InvalidOperationException(
$"{action}失败:{string.Join("", result.Errors.Select(x => x.Description))}");
}
}
@@ -0,0 +1,7 @@
namespace Jiaowu.Api.Infrastructure.Persistence;
public sealed class DatabaseOptions
{
public const string SectionName = "Database";
public string Provider { get; set; } = "MySql";
}
@@ -0,0 +1,734 @@
// <auto-generated />
using System;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
[DbContext(typeof(AppDbContext))]
[Migration("20260724042846_InitialMySql")]
partial class InitialMySql
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AcademicTerm", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("AcademicYear")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateOnly>("EndDate")
.HasColumnType("date");
b.Property<bool>("IsCurrent")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("Season")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateOnly>("StartDate")
.HasColumnType("date");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsCurrent");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("AcademicTerms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AdministrativeClass", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<string>("CounselorName")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Grade")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<Guid>("MajorId")
.HasColumnType("char(36)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("MajorId");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("AdministrativeClasses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Building", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("CampusId")
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("CampusId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Buildings");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Campus", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Address")
.HasColumnType("longtext");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Campuses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Classroom", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("BuildingId")
.HasColumnType("char(36)");
b.Property<int>("Capacity")
.HasColumnType("int");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Equipment")
.HasColumnType("longtext");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("RoomType")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("BuildingId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Classrooms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.College", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("CampusId")
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("ShortName")
.HasColumnType("longtext");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("CampusId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Colleges");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Major", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<Guid>("CollegeId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("DegreeType")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SchoolingYears")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("CollegeId");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Majors");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.ApplicationRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<int>("DataScope")
.HasColumnType("int");
b.Property<string>("Description")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.ApplicationUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<Guid?>("CollegeId")
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTime?>("LastLoginAt")
.HasColumnType("datetime(6)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<string>("StaffNumber")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.HasIndex("StaffNumber");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.System.AuditLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("IpAddress")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<string>("Method")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<string>("Path")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid?>("UserId")
.HasColumnType("char(36)");
b.Property<string>("UserName")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.ToTable("AuditLogs");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AdministrativeClass", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Major", "Major")
.WithMany()
.HasForeignKey("MajorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Major");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Building", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Campus", "Campus")
.WithMany()
.HasForeignKey("CampusId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Campus");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Classroom", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Building", "Building")
.WithMany()
.HasForeignKey("BuildingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Building");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.College", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Campus", "Campus")
.WithMany()
.HasForeignKey("CampusId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Campus");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Major", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.College", "College")
.WithMany()
.HasForeignKey("CollegeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("College");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,577 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using MySql.EntityFrameworkCore.Metadata;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
/// <inheritdoc />
public partial class InitialMySql : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AcademicTerms",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
AcademicYear = table.Column<string>(type: "longtext", nullable: false),
Season = table.Column<int>(type: "int", nullable: false),
StartDate = table.Column<DateOnly>(type: "date", nullable: false),
EndDate = table.Column<DateOnly>(type: "date", nullable: false),
IsCurrent = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AcademicTerms", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Description = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
DataScope = table.Column<int>(type: "int", nullable: false),
Name = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
DisplayName = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
StaffNumber = table.Column<string>(type: "varchar(30)", maxLength: 30, nullable: true),
CollegeId = table.Column<Guid>(type: "char(36)", nullable: true),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
LastLoginAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
UserName = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "tinyint(1)", nullable: false),
PasswordHash = table.Column<string>(type: "longtext", nullable: true),
SecurityStamp = table.Column<string>(type: "longtext", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "longtext", nullable: true),
PhoneNumber = table.Column<string>(type: "longtext", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "tinyint(1)", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
LockoutEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
AccessFailedCount = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AuditLogs",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
UserId = table.Column<Guid>(type: "char(36)", nullable: true),
UserName = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
Method = table.Column<string>(type: "varchar(10)", maxLength: 10, nullable: false),
Path = table.Column<string>(type: "varchar(300)", maxLength: 300, nullable: false),
StatusCode = table.Column<int>(type: "int", nullable: false),
IpAddress = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AuditLogs", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "Campuses",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
Address = table.Column<string>(type: "longtext", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Campuses", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<Guid>(type: "char(36)", nullable: false),
ClaimType = table.Column<string>(type: "longtext", nullable: true),
ClaimValue = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn),
UserId = table.Column<Guid>(type: "char(36)", nullable: false),
ClaimType = table.Column<string>(type: "longtext", nullable: true),
ClaimValue = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "varchar(255)", nullable: false),
ProviderKey = table.Column<string>(type: "varchar(255)", nullable: false),
ProviderDisplayName = table.Column<string>(type: "longtext", nullable: true),
UserId = table.Column<Guid>(type: "char(36)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<Guid>(type: "char(36)", nullable: false),
RoleId = table.Column<Guid>(type: "char(36)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<Guid>(type: "char(36)", nullable: false),
LoginProvider = table.Column<string>(type: "varchar(255)", nullable: false),
Name = table.Column<string>(type: "varchar(255)", nullable: false),
Value = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "Buildings",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
CampusId = table.Column<Guid>(type: "char(36)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Buildings", x => x.Id);
table.ForeignKey(
name: "FK_Buildings_Campuses_CampusId",
column: x => x.CampusId,
principalTable: "Campuses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "Colleges",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
CampusId = table.Column<Guid>(type: "char(36)", nullable: true),
ShortName = table.Column<string>(type: "longtext", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Colleges", x => x.Id);
table.ForeignKey(
name: "FK_Colleges_Campuses_CampusId",
column: x => x.CampusId,
principalTable: "Campuses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "Classrooms",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
BuildingId = table.Column<Guid>(type: "char(36)", nullable: false),
Capacity = table.Column<int>(type: "int", nullable: false),
RoomType = table.Column<string>(type: "longtext", nullable: false),
Equipment = table.Column<string>(type: "longtext", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Classrooms", x => x.Id);
table.ForeignKey(
name: "FK_Classrooms_Buildings_BuildingId",
column: x => x.BuildingId,
principalTable: "Buildings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "Majors",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
CollegeId = table.Column<Guid>(type: "char(36)", nullable: false),
DegreeType = table.Column<string>(type: "longtext", nullable: false),
SchoolingYears = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Majors", x => x.Id);
table.ForeignKey(
name: "FK_Majors_Colleges_CollegeId",
column: x => x.CollegeId,
principalTable: "Colleges",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "AdministrativeClasses",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
MajorId = table.Column<Guid>(type: "char(36)", nullable: false),
Grade = table.Column<int>(type: "int", nullable: false),
CounselorName = table.Column<string>(type: "longtext", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Code = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
SortOrder = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AdministrativeClasses", x => x.Id);
table.ForeignKey(
name: "FK_AdministrativeClasses_Majors_MajorId",
column: x => x.MajorId,
principalTable: "Majors",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_AcademicTerms_Code",
table: "AcademicTerms",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AcademicTerms_IsCurrent",
table: "AcademicTerms",
column: "IsCurrent");
migrationBuilder.CreateIndex(
name: "IX_AcademicTerms_IsEnabled_SortOrder",
table: "AcademicTerms",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_AdministrativeClasses_Code",
table: "AdministrativeClasses",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AdministrativeClasses_IsEnabled_SortOrder",
table: "AdministrativeClasses",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_AdministrativeClasses_MajorId",
table: "AdministrativeClasses",
column: "MajorId");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "IX_AspNetUsers_StaffNumber",
table: "AspNetUsers",
column: "StaffNumber");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AuditLogs_CreatedAt",
table: "AuditLogs",
column: "CreatedAt");
migrationBuilder.CreateIndex(
name: "IX_Buildings_CampusId",
table: "Buildings",
column: "CampusId");
migrationBuilder.CreateIndex(
name: "IX_Buildings_Code",
table: "Buildings",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Buildings_IsEnabled_SortOrder",
table: "Buildings",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_Campuses_Code",
table: "Campuses",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Campuses_IsEnabled_SortOrder",
table: "Campuses",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_Classrooms_BuildingId",
table: "Classrooms",
column: "BuildingId");
migrationBuilder.CreateIndex(
name: "IX_Classrooms_Code",
table: "Classrooms",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Classrooms_IsEnabled_SortOrder",
table: "Classrooms",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_Colleges_CampusId",
table: "Colleges",
column: "CampusId");
migrationBuilder.CreateIndex(
name: "IX_Colleges_Code",
table: "Colleges",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Colleges_IsEnabled_SortOrder",
table: "Colleges",
columns: new[] { "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_Majors_Code",
table: "Majors",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Majors_CollegeId",
table: "Majors",
column: "CollegeId");
migrationBuilder.CreateIndex(
name: "IX_Majors_IsEnabled_SortOrder",
table: "Majors",
columns: new[] { "IsEnabled", "SortOrder" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AcademicTerms");
migrationBuilder.DropTable(
name: "AdministrativeClasses");
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AuditLogs");
migrationBuilder.DropTable(
name: "Classrooms");
migrationBuilder.DropTable(
name: "Majors");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Buildings");
migrationBuilder.DropTable(
name: "Colleges");
migrationBuilder.DropTable(
name: "Campuses");
}
}
}
@@ -0,0 +1,731 @@
// <auto-generated />
using System;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AcademicTerm", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("AcademicYear")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateOnly>("EndDate")
.HasColumnType("date");
b.Property<bool>("IsCurrent")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("Season")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateOnly>("StartDate")
.HasColumnType("date");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsCurrent");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("AcademicTerms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AdministrativeClass", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<string>("CounselorName")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("Grade")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<Guid>("MajorId")
.HasColumnType("char(36)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("MajorId");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("AdministrativeClasses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Building", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("CampusId")
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("CampusId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Buildings");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Campus", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Address")
.HasColumnType("longtext");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Campuses");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Classroom", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid>("BuildingId")
.HasColumnType("char(36)");
b.Property<int>("Capacity")
.HasColumnType("int");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Equipment")
.HasColumnType("longtext");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("RoomType")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("BuildingId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Classrooms");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.College", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("CampusId")
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("ShortName")
.HasColumnType("longtext");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("CampusId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Colleges");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Major", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("varchar(40)");
b.Property<Guid>("CollegeId")
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("DegreeType")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SchoolingYears")
.HasColumnType("int");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("CollegeId");
b.HasIndex("IsEnabled", "SortOrder");
b.ToTable("Majors");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.ApplicationRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<int>("DataScope")
.HasColumnType("int");
b.Property<string>("Description")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.Identity.ApplicationUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<Guid?>("CollegeId")
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTime?>("LastLoginAt")
.HasColumnType("datetime(6)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<string>("StaffNumber")
.HasMaxLength(30)
.HasColumnType("varchar(30)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.HasIndex("StaffNumber");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.System.AuditLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("IpAddress")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<string>("Method")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<string>("Path")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<Guid?>("UserId")
.HasColumnType("char(36)");
b.Property<string>("UserName")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.ToTable("AuditLogs");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.AdministrativeClass", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Major", "Major")
.WithMany()
.HasForeignKey("MajorId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Major");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Building", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Campus", "Campus")
.WithMany()
.HasForeignKey("CampusId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Campus");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Classroom", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Building", "Building")
.WithMany()
.HasForeignKey("BuildingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Building");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.College", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.Campus", "Campus")
.WithMany()
.HasForeignKey("CampusId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Campus");
});
modelBuilder.Entity("Jiaowu.Api.Domain.Academic.Major", b =>
{
b.HasOne("Jiaowu.Api.Domain.Academic.College", "College")
.WithMany()
.HasForeignKey("CollegeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("College");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("Jiaowu.Api.Domain.Identity.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
+22
View File
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="10.0.7" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
</Project>
+14
View File
@@ -0,0 +1,14 @@
@Host = http://localhost:5255
GET {{Host}}/health
Accept: application/json
###
POST {{Host}}/api/auth/login
Content-Type: application/json
{
"userName": "admin",
"password": "Admin@123456"
}
+206
View File
@@ -0,0 +1,206 @@
using System.Text;
using System.Text.Json.Serialization;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Middleware;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
var databaseOptions = builder.Configuration
.GetSection(DatabaseOptions.SectionName)
.Get<DatabaseOptions>() ?? new DatabaseOptions();
if (databaseOptions.Provider.Equals("SQLite", StringComparison.OrdinalIgnoreCase) &&
!builder.Environment.IsDevelopment())
{
throw new InvalidOperationException("SQLite 仅允许在 Development 环境使用。生产环境请配置 MySql。");
}
builder.Services.AddDbContext<AppDbContext>(options =>
{
if (databaseOptions.Provider.Equals("SQLite", StringComparison.OrdinalIgnoreCase))
{
var sqliteConnectionString = builder.Configuration.GetConnectionString("SQLite")
?? throw new InvalidOperationException("缺少 ConnectionStrings:SQLite。");
var sqliteBuilder = new SqliteConnectionStringBuilder(sqliteConnectionString);
if (!Path.IsPathRooted(sqliteBuilder.DataSource))
{
sqliteBuilder.DataSource = Path.GetFullPath(
sqliteBuilder.DataSource,
builder.Environment.ContentRootPath);
}
Directory.CreateDirectory(
Path.GetDirectoryName(sqliteBuilder.DataSource)
?? builder.Environment.ContentRootPath);
options.UseSqlite(sqliteBuilder.ConnectionString);
return;
}
if (!databaseOptions.Provider.Equals("MySql", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"不支持数据库 Provider '{databaseOptions.Provider}',可选值为 SQLite、MySql。");
}
var connectionString = builder.Configuration.GetConnectionString("MySql");
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new InvalidOperationException(
"缺少 MySQL 连接串。请通过 ConnectionStrings__MySql 环境变量配置。");
}
options.UseMySQL(connectionString);
});
builder.Services
.AddIdentityCore<ApplicationUser>(options =>
{
options.Password.RequiredLength = 8;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.User.RequireUniqueEmail = false;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
})
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<AppDbContext>();
var jwtOptions = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>()
?? throw new InvalidOperationException("缺少 Jwt 配置。");
if (Encoding.UTF8.GetByteCount(jwtOptions.Key) < 32)
{
throw new InvalidOperationException("Jwt:Key 至少需要 32 字节。");
}
builder.Services.Configure<JwtOptions>(
builder.Configuration.GetSection(JwtOptions.SectionName));
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<DatabaseInitializer>();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(jwtOptions.Key)),
ClockSkew = TimeSpan.FromMinutes(1)
};
});
builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
{
options.AddPolicy("Web", policy =>
{
var origins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>()
?? ["http://localhost:5173"];
policy.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler(options =>
{
options.ExceptionHandler = async context =>
{
var exception = context.Features
.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>()?.Error;
var isConstraintConflict = exception is DbUpdateException;
var statusCode = isConstraintConflict
? StatusCodes.Status409Conflict
: StatusCodes.Status500InternalServerError;
context.Response.StatusCode = statusCode;
await Results.Problem(
title: isConstraintConflict ? "数据约束冲突" : "服务器处理请求时发生错误",
detail: isConstraintConflict
? "编码可能已存在,或该数据正在被其他业务引用。"
: builder.Environment.IsDevelopment()
? exception?.Message
: "请稍后重试,并联系系统管理员查看日志。",
statusCode: statusCode)
.ExecuteAsync(context);
};
});
builder.Services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "大学教务管理系统 API",
Version = "v1"
});
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
[
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}
] = []
});
});
var app = builder.Build();
app.UseExceptionHandler();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("Web");
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<AuditMiddleware>();
app.MapControllers();
app.MapGet("/health", () => Results.Ok(new
{
Status = "healthy",
Database = databaseOptions.Provider,
Environment = app.Environment.EnvironmentName,
Time = DateTimeOffset.UtcNow
})).AllowAnonymous();
using (var scope = app.Services.CreateScope())
{
await scope.ServiceProvider.GetRequiredService<DatabaseInitializer>()
.InitializeAsync();
}
app.Run();
public partial class Program;
@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:55471",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5255",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -0,0 +1,22 @@
{
"Database": {
"Provider": "SQLite"
},
"ConnectionStrings": {
"SQLite": "Data Source=data/jiaowu-dev.sqlite"
},
"Jwt": {
"Key": "jiaowu-development-secret-key-change-before-production"
},
"SeedAdmin": {
"UserName": "admin",
"Password": "Admin@123456",
"DisplayName": "系统管理员"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"Database": {
"Provider": "MySql"
},
"ConnectionStrings": {
"MySql": ""
},
"Jwt": {
"Issuer": "Jiaowu.Api",
"Audience": "Jiaowu.Web",
"Key": "REPLACE_IN_PRODUCTION_WITH_A_LONG_RANDOM_SECRET",
"ExpireMinutes": 480
},
"Cors": {
"Origins": [
"http://localhost:5173"
]
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"AllowedHosts": "*"
}