Teach you how to create a local database, create tables, and complete additions, deletions, modifications, and queries for .Net projects (based on visual stdio)

1. Environment configuration and model creation

Step 1: Create a new project

Create a new project named Exams

 

Select Exams and click Run to see if the test can run successfully:

If the following interface appears, it means the operation is successful:

The folder structure is as follows:

wwwroot folder: Contains static files such as HTML files, JavaScript files, and CSS files.

appSettings.json: Contains configuration data such as connection strings.

Program.cs: Contains the entry point of the program.

Step 2: Configure the environment

Add tools, install Entity Framework core, etc...

First find the module you want to add dependencies, then right-click the dependencies and click Manage NuGet Packages:

You can see the <Installed> tools, enter the following 5 tool names in <Browse> to install them:

1.Microsoft.EntityFrameworkCore

2.Microsoft.EntityFrameworkCore.Sqlite

3.Microsoft.EntityFrameworkCore.SqlServer

4.Microsoft.EntityFrameworkCore.Tools

5.Microsoft.VisualStudio.Web.CodeGeneration.Design

The installation results are as follows:

Among them, 1, 2, 4 and 5 must be installed.

Step 3: Add data model

Right-click the module and create new folders models folder and Data folder:

 

Right-click the newly created project-Add-Class and create a new class ExamSite:

The examination room table is designed as follows:

考场表:考场ID,考场名,所属校区,所属楼名,房间号
ExamSiteId ->Int
ExamSiteName -> String
School -> String
Building -> Int
Room -> Int

Copy the following code and paste it into ExamSite.cs, which is mainly used to define the structure of the table:

using System.ComponentModel.DataAnnotations;
namespace Exams.Models;
public class ExamSite
{
    public int ExamSiteId { get; set; }
    public string? ExamSiteName { get; set; }
    public string? School { get; set; }
    public string? Building { get; set; }
    public int? Room { get; set; }
}

2. Build the base frame

First, right-click the Pages folder and create an Exam folder

Then right-click the Exam folder and select Add, select <New Scaffolding Project>

Then select <Use Entity Framework to generate Razor pages (CURD)> and select Add.

at last:

1. Select ExamSite (Exams.Models) in the model class. This is a file in the Models folder.

2. In the data context class, first select ExamSiteContext(Exams.Data), then select + to generate the class name Exams.Data.ExamsContext.

Select Add.

 After about 1 minute of generation, the following files were generated:

3. Modify the Program.cs file

The class name selected in the previous step <Data Context Class> will generate a new class under the Data folder:

The name is automatically generated, usually <module name Context.cs>.

We next need to add the following code to Program.cs of this module:

using Exams.Data;

using Exams.Data is to allow Program.cs to introduce the ExamsContext file.

builder.Services.AddDbContext<ExamsContext>(options =>
    options.UseSqlite("Data Source=Exam.db"));

Among them, ExamsContext is the file that was just automatically generated, and Exam.db is the name of the target database we want to generate.

4. Database migration

Select NuGet Package Manager-Package Manager Console for Tools in VS

2. Enter Add-Migration InitialCreate to create a data table

3.Update-Database

You can see that an Exam.db file appears at the end of the module:

Drag the Exam.db file directly into Navicat to see the table directly:

You can find that fields like ExamSiteId are the fields defined in the data model we created in <1>.

5. Add, delete, modify and check test

After selecting Exam and clicking to run the project, you can add the suffix </folder name/file name> to the browser address to access:

For example, there are 4 categories under the Exam folder: used for adding, deleting, modifying and checking respectively.

Create represents new addition, and Edit represents modification. If you want to call the new interface, you only need to add the /Exam/Create suffix: https://localhost:7110/Exam/Create.

If we enter the following data for a simple test:

First, the new data will appear on the web page:

Then the data will be updated in real time in the database:

It can be inferred that the data will be inserted directly into the Exam.db file and can be accessed in real time.

The following are some instructions for adding, deleting, modifying, and checking:

Delete, modify and check as follows:

This enables the creation of databases and tables as well as basic additions, deletions, modifications and queries through .Net.

6. Create multiple tables in the same database

1. Exam table data structure definition:

Exam table: exam ID, exam name, registration start time, registration end time, scheduled exam start time, scheduled exam end time, exam start time, exam end time

考试表:考试ID,考试名,报名开始时间,报名结束时间,排考开始时间,排考结束时间,考试开始时间,考试结束时间
Exmination表
字段定义如下:
ExamId ->Int
ExamName -> String
SignUpBeginTime -> DateTime
SignUpEndTime -> DateTime
ArrangeExamBeginTime -> DateTime
ArrangeExamEndTime -> DateTime
ExamBeginTime -> DateTime
ExamEndTime -> DateTime
namespace Exams.Models
{
    public class Examination
    {
        public int ExamId { get; set; }
        public string? ExamName { get; set; }
        public DateTime? SignUpBeginTime { get; set; }
        public DateTime? SignUpEndTime { get; set; }
        public DateTime? ArrangeExamBeginTime { get; set; }
        public DateTime? ArrangeExamEndTime { get; set; }
        public DateTime? ExamBeginTime { get; set; }
        public DateTime? ExamEndTime { get; set; }
    }
}

2. Examination-examination room association table data structure definition:

Exam-exam room association table: record ID, exam ID, exam room ID

考试-考场关联表:记录ID,考试ID,考场ID
ExamAndExamSite表
字段定义如下:
recordId -> Int
ExamId -> Int
ExamSiteId -> Int
namespace Exams.Models
{
    public class ExamAndExamSite
    {
        public int recordId { get; set; }
        public int? ExamId { get; set; }
        public int? ExamSiteId { get; set; }
    }
}

After defining the data model of the above three tables.

Step 1:Create two more folders, Exam1 and Exam2, under Pages. The corresponding relationships are as follows:

Exam -> ExamSite.cs (add, delete, modify and check operations on the exam room table)

Exam1 -> Examination.cs (add, delete, modify and check operations on the exam table)

Exam2 -> ExamAndExamSite.cs (add, delete, modify and check operations of exams and exam room tables)

Step 2:Modify the ExamsContext.cs file in the Data folder

The ExamsContext.cs file will be formed after generating the Entity Framework for ExamSite:

The code of the new ExamsContext.cs file is as follows:

using Microsoft.EntityFrameworkCore;
using Exams.Models;

namespace Exams.Data{
    public class ExamsContext : DbContext{
        public ExamsContext (DbContextOptions<ExamsContext> options)
            : base(options){
        }
        public DbSet<Exams.Models.ExamSite> ExamSite { get; set; } = default!;
        public DbSet<Exams.Models.Examination> Examination { get; set; } = default!;
        //定义了Examination它是DbSet<Examination>类型的,框架会将Examination类与一个表关联起来,表名默认为类名
        public DbSet<Exams.Models.ExamAndExamSite> ExamAndExamSite { get; set; } = default!;

        protected override void OnModelCreating(ModelBuilder modelBuilder){
            modelBuilder.Entity<Examination>().HasKey(e => e.ExamId); // 配置 Examination 的主键
            modelBuilder.Entity<ExamAndExamSite>().HasKey(e => e.recordId); // 配置 ExamAndExamSite 的主键
        }
    }
}

It mainly adds the definitions of two other tables and sets the primary keys of the two tables.

Step 3:Select the Exam, Exam1, and Exam2 folders under the Pages folder to build the scaffolding respectively, and select ExamSite.cs, Examination.cs, and ExamAndExamSite as model classes respectively. For these .cs files, always select Exams.Data.ExamsContext for the data context class.

The final structure of the project is as follows:

   

Step 4: Perform database migration according to the previous method. After success, the Exam.db file is generated, which can then be viewed in Navicat. You will find that the Exam.db database is now There are already 3 tables in:

ExamSite: The examination room schedule is as follows:

Examination: The examination table is as follows:

ExamAndExamSite: Exam-exam room table is as follows:

7. Support API controller (access classes/methods through url)

First, create a new Controllers folder under the module to be run, and then create a class under the Controllers folder. The class name ends with Controller:

Note that the namespace should be written: module name.folder name. public class class name: Controller. The following figure is a basic program:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Exams.Data;
using Exams.Models;

namespace Exams.Controllers
{
    [Route("test")] // 基路由,将处理 /test 的请求
    public class WayController : Controller
    {
        [HttpGet("a")] // 完整的路由将变成 /test/a
        public IActionResult Print()
        {
            var data = new { message = "aaa" }; // 创建一个匿名对象作为 JSON 数据
            return Json(data); // 返回 JSON 结果
        }
    }
}

Then be sure to modify Program.cs and add the following two pieces of code:

builder.Services.AddControllers();
app.MapControllers();

builder.Services.AddControllers(); // Add this line to support API controllers

app.MapControllers(); //Register API controller routes here 

Then add /test/a after the url to output aaa!

8. Obtain all exam results during the registration period

List<Exam> GetActiveExam(DateTime now) interface implementation (afternoon)

Interface function: Get all exams during the registration period

Business logic: First get the current system time now, exam registration start time beginTime, exam registration end time endTime, beginTime<=now<=endTime.

The returned results are as follows:

Program idea:

First, define a function getNowTime to obtain the current system time:

Use the DateTimeOffset function to obtain the time.

public DateTimeOffset getNowTime(){
    //DateTime localTime = DateTime.Now;
    DateTimeOffset dateTimeOffset = DateTimeOffset.Now;
    return dateTimeOffset;
}

Then, a Result structure is defined to store the returned prompt information and data in the exam table.​ 

public struct Result{
    public string response { get; set; }
    public Examination examination { get; set; }
}

 Finally, there is the specific business logic: call _context.Examination.ToList() to obtain the collection of all data in the examination table, and call getNowTime to obtain the current system time.

Then extract each piece of data in the exam table through a foreach loop, and extract the registration start time and end time of each piece of data one by one.

Then judge the relationship between the current system time and the start time and end time, which is divided into three situations: 1. Registration has not started, 2. Registration has ended, 3. Registration is in progress. If it is the first two cases, the detailed information of the exam will be returned as empty. If it can be registered, the detailed information of the exam will be returned.

Here is the complete code: 

using Microsoft.AspNetCore.Mvc;
using Exams.Models;

namespace Exams.Controllers{
    [Route("test")] // 基路由,将处理 /test 的请求
    public class WayController : Controller{
        private readonly Exams.Data.ExamsContext _context;
        public struct Result{
            public string response { get; set; }
            public Examination examination { get; set; }
        }
        public WayController(Exams.Data.ExamsContext context){
            _context = context;
        }
        public DateTimeOffset getNowTime(){
            //DateTime localTime = DateTime.Now;
            DateTimeOffset dateTimeOffset = DateTimeOffset.Now;
            return dateTimeOffset;
        }
        [HttpGet("a")]
        public ActionResult<List<Result>> Compare()
        {
            List<Result> finalResult = new List<Result>();
            List<Examination> LIST = _context.Examination.ToList();
            DateTimeOffset nowTime = getNowTime();
            Result result = new Result();
            foreach (Examination list in LIST)
            {
                DateTimeOffset newSignUpBeginTime = new DateTimeOffset((DateTime)list.SignUpBeginTime);
                DateTimeOffset newSignUpEndTime = new DateTimeOffset((DateTime)list.SignUpEndTime);
                if (nowTime < newSignUpBeginTime)
                {
                    result.response = list.ExamId + list.ExamName + ":报名未开始";
                    result.examination = null;
                }
                else if (nowTime > newSignUpEndTime)
                {
                    result.response = list.ExamId + list.ExamName + ":报名已结束";
                    result.examination = null;
                }
                else
                {
                    result.response = list.ExamId + list.ExamName + ":报名成功";
                    result.examination = list;
                }
                finalResult.Add(result);
            }
            return finalResult;
        }
    }   

}

The result is as follows:

9. Others

4. ExamInfo GetExamInfo(Guid examId); interface implementation + ExamInfo data structure implementation (evening)

Interface function: Get an exam, including all exam rooms used in this exam.

Interface implementation logic: First, pass in an exam ID, query the exam table, and return information about the exam. Then query the exam-exam room table based on the exam ID and return all exam rooms associated with the exam ID.

ExamInfo data structure implementation logic: contains all Exam fields, and adds the List<Room> Rooms field to represent all examination rooms used in the exam.

6. Excel export function

7. Excel import function

6. Implementation of search function

Guess you like

Origin blog.csdn.net/RuanFun/article/details/134712530