core练习笔记(数据的增、删、改、查)

前端

 

@{
    Layout = null;
}
@model List<DomeCore.Models.Student>
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/js/jquery-3.4.1.js"></script>
</head>
<body>
    <script>
        
        Stu_show();
        //数据显示
        function Stu_show() {
            $.ajax({
                url: "/Home/Stu_Show",
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    show(data);
                },
                error: function (data) {
                    alert("Error!");
                }
            })
        }
        //查询
        function Stu_Sel() {
            var name = $("#Student_Name1").val();
            if (name == "全部") {
                Stu_show();
                $("#Student_Name1").val("");
            }
            else {
                $.ajax({
                    url: "/Home/Stu_Sel",
                    type: "get",
                    data: { "Name": name },
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        show(data);
                        $("#Student_Name1").val("");
                    },
                    error: function (data) {
                        alert("Error!");
                    }
                })
            }
        }
        //删除
        function Stu_Del(id) {
            $.ajax({
                url: "/Home/Stu_Del",
                type: "Delete",
                data: { "ID": id },
                success: function (data) {
                    Stu_show();
                },
                error: function (data) {
                    alert("Error!");
                }
            })
 
        }
        //添加和修改
        function Stu_add() {
            var id = $("#Stu_ID").html();
            var name = $("#Student_Name").val();
            console.log(name);
            console.log(id);
            if (id != "") {//修改
                $.ajax({
                    url: "/Home/Stu_Update",
                    type: "Patch",
                    data: { "ID": id, "Name": name },
                    success: function (data) {
                        Stu_show();
                        $("#Student_Name").val("");
                        $("#Stu_ID").html("");
                    },
                    error: function (data) {
                        alert("Error1!");
 
                    }
                })
            }
            else {//添加
                $.ajax({
                    url: "/Home/Stu_Add",
                    type: "post",
                    data: { "Name": $("#Student_Name").val() },
                    success: function (data) {
                        Stu_show();
                        $("#Stu_ID").html("");
                        $("#Student_Name").val("");
                    },
                    error: function (data) {
                        alert("Error2!");
                    }
                })
            }
        }
        //显示修改数据
        function ClickUpdate(id) {
            $.ajax({
                url: "/Home/Stu_Sel_By_ID",
                type: "get",
                data: { "ID":id },
                success: function (data) {
                    $("#Stu_ID").html(data.id);
                    $("#Student_Name").val(data.name);
                },
                error: function (data) {
                    alert("Error!");
                }
            })
            
        }
        //修改数据
        function show(data) {
            $("#Stu_info_show").empty();
            $.each(data, function (key, item) {
                $("#Stu_info_show").append('<p>' + item.id + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + item.name + '&nbsp;&nbsp;&nbsp;<input type="button" onclick="Stu_Del(' + item.id + ')" value="删除"/>&nbsp;&nbsp;&nbsp;<input type="button" onclick="ClickUpdate(' + item.id + ')" value="修改"/></p>');
            })
        }
    </script>
    <div>
        <h3>显示数据</h3>
        <div id="Stu_info_show">
            
        </div>
    </div>
    <br />
    <br />
    <div>
        <h3 id="Stu_title">添加</h3>
        <span id="Stu_ID"></span><br />
        <input id="Student_Name" name="Name" type="text" />&nbsp;&nbsp;<input type="button" onclick="Stu_add()" value="确定" />
    </div>
    <br />
    <br />
    <div>
        <h3>查询</h3>
        <input id="Student_Name1" name="Name" type="text" />&nbsp;&nbsp;<input type="button" onclick="Stu_Sel()" value="查询" />
    </div>
</body>
</html>

 

 

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DomeCore.Models;
namespace DomeCore.Controllers
{
    public class HomeController : Controller
    {
 
        private readonly IStudentRepository _studentrepository;
 
        public HomeController(IStudentRepository studentrepository) 
        {
            _studentrepository = studentrepository;
        }
        public IActionResult Index()
        {
            return View();
        }
        //添加
        [HttpPost]
        public string Stu_Add(string Name)
        {
            Student stu = new Student() { Name=Name};
            _studentrepository.Add(stu);
            return "1";
        }
        //显示数据
        [HttpPost]
        public JsonResult Stu_Show()
        {
            return Json(_studentrepository.Stu_show());
        }
        //查询信息
        [HttpGet]
        public JsonResult Stu_Sel(string Name) 
        {
            return Json(_studentrepository.Stu_Sel(Name));
        }
        //删除
        [HttpDelete]
        public string Stu_Del(int ID) 
        {
            if (_studentrepository.Delete(ID)!=null)
            {
                return "1";
            }
            return "2";
        }
        //修改
        [HttpPatch]
        public string Stu_Update(string ID,string Name) 
        {
            Student stu = new Student() {ID=int.Parse(ID),Name=Name };
            Student s = _studentrepository.SelbyID(stu.ID);
            if (s != null)
            {
                _studentrepository.Update(stu);
                return "1";
            }
            else 
            {
                return "2";
            }
            
        }
        //查询
        [HttpGet]
        public Student Stu_Sel_By_ID(int ID) 
        {
            return _studentrepository.SelbyID(ID);
        }
    }
}

IStudentRepository接口(作用:操作方法)

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

namespace DomeCore.Models
{
    public interface IStudentRepository
    {
        List<Student> Stu_show();
        List<Student> Stu_Sel(string name);
        Student Add(Student students);
        Student Update(Student updateStudent);
        Student Delete(int id);
        Student SelbyID(int id);
    }
}

SQLStudentRepository类(作用:实现IStudentRepository接口方法

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

namespace DomeCore.Models
{
    //使用EFcore来访问数据库,对数据进行相关的操作
    public class SQLStudentRepository : IStudentRepository
    {
        //依赖注入
        private readonly AppDbContext _context;
        public SQLStudentRepository(AppDbContext context)
        {
            _context = context;
        }
        //显示全部数据
        public List<Student> Stu_show() {
            return _context.Students.ToList();
        }
        //显示根据名称模糊查询数据
        public List<Student> Stu_Sel(string name) 
        {
            return _context.Students.Where(x=>x.Name.Contains(name)).ToList();
        }
        //添加
        public Student Add(Student students)
        {
            _context.Students.Add(students);//这个add为系统封装好了的方法,详情可以右键转定义
            _context.SaveChanges();
            return students;
        }
        //删除
        public Student Delete(int id)
        {
            Student s = _context.Students.FirstOrDefault(x=>x.ID==id);
            if (s!=null)
            {
                _context.Students.Remove(s);//remove为core自带的
                _context.SaveChanges();
            }
            return s;
        }
        //修改
        public Student Update(Student updateStudent)
        {
            Student s = _context.Students.FirstOrDefault(x=>x.ID==updateStudent.ID);
            s.Name = updateStudent.Name;
            _context.SaveChanges();
            return updateStudent;
        }
        //按id查询
        public Student SelbyID(int id)
        {
            return _context.Students.FirstOrDefault(x=>x.ID==id);
        }
    }
}

AppDbContext(EFcore,代码先行)

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DomeCore.Models
{
    public class AppDbContext:DbContext
    {
        //构造函数
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options) 
        {  
        }
        //添加种子数据
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //默认数据
            modelBuilder.Entity<Student>().HasData(
                new Student {ID=1, Name="小向" },
                new Student { ID=2,Name="小红"}
                );
        }


        public DbSet<Student> Students { get; set; }
    }
}

services.AddScoped<IStudentRepository,SQLStudentRepository>();//依赖注入声明

原文地址:https://www.cnblogs.com/LanHai12/p/15258100.html