C# EF's CodeFirst basically uses additions, deletions, changes, and checking, super simple and suitable for novices

Super simple EF basic use suitable for newbies

1. First, after the database is designed, create entities and generate context help classes through codefirst

Use codefirst
VS will automatically generate the following files (database entities and context help)

Entities and generating context help classes
2. Write the basic usage method in the BLL layer (you can write the method directly in the controller after you are proficient).
Pay attention to the need to use the generic
query (display) and add methods,
How to query and add
delete and modify methods
In the method of deletion and modification
******Pay attention to additions, deletions, and modifications Be sure to SaveChanges() after the method; some of the
code is
shown below 内联代码片.

//实例化上下文帮助类
MyContext db = new MyContext();

//查询
public DbSet<T> Query()
        {
    
    
            return db.Set<T>();
        }

//新增
 public int Insert(T t)
        {
    
    
             db.Set<T>().Add(t);
            return db.SaveChanges();
        }
        
//删除
 public int Delete(int id)
 {
    
    
     //先找到数据
    var obj= db.Set<T>().Find(id);
     //进行删除
     db.Set<T>().Remove(obj);
     return db.SaveChanges();
 }

//修改
public int Edit(T t)
{
    
    
    db.Set<T>().Attach(t);
    db.Entry<T>(t).State = EntityState.Modified;
    return db.SaveChanges();
}


After writing the basic method, call the method in the controller.
Third, the controller calls the method

Code directly

Show some below 内联代码片.

//实例化
        StoreCarBLL<StoreInfo> Store = new StoreCarBLL<StoreInfo>();
        StoreCarBLL<CarInfo> Car = new StoreCarBLL<CarInfo>();

//分页显示数据

注:返回类型为IHttpActionResult 代表可以返回任意类型 
        [Route("api/showCar")]
        [HttpGet]
        public IHttpActionResult ShowCar(int PageIndex,int PageSize )
        {
    
    
	//如果只是单纯的查询显示 无条件,不分页 下面的这一句话即可
            var list = Car.Query().ToList();
            **********分割  以下为分页数据************
            //计算开始页码
            int Start = (PageIndex - 1) * PageSize;
            //查询所有汽车 分页 按CId排序(必须有排序) 
            var list = Car.Query().OrderBy(x=>x.CId).Skip(Start).Take(PageSize).ToList();
            //所有总数据量
            int PageCount = Car.Query().Count();         
            return  Ok(new {
    
     list , PageCount });
        }
//多表联查写法
//属于 1公司的汽车 多表联查
        var list = (from a in db.StoreInfo
         join b in db.CarInfo on a.SId equals b.StoreId
         select new {
    
     a.CompanyName,b.CarName }).ToList();

注:查询显示的写法有很多种 可以网上自己查找资料


/// <summary>
        /// 新增汽车
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        [Route("api/addCar")]
        [HttpPost]
        public IHttpActionResult AddCar(CarInfo c)
        {
    
    
            return Ok(Car.Insert(c));
        }

 /// <summary>
        /// 删除汽车
        /// </summary>
        /// <param name="cd"></param>
        /// <returns></returns>
        [Route("api/RemoveCar")]
        [HttpGet]
        public IHttpActionResult DelCar(int cd )
        {
    
    
            return Ok(Car.Delete(cd) );
        }
        
/// <summary>
        /// 反填数据(修改的时候)
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        [Route("api/fanCar")]
        [HttpGet]
        public IHttpActionResult FanCar(int cid)
        {
    
    
            return Ok(Car.Query().Find(cid));
        }

 /// <summary>
        /// 修改(编辑)
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        [Route("api/editCar")]
        [HttpPost]
        public IHttpActionResult EditCar(CarInfo c)
        {
    
    
            return Ok(Car.Edit(c));
        }

		*********以上基本的增删改查**********
  /// <summary>
        /// 状态流转
        /// </summary>
        /// <param name="cid"> Id</param>
        /// <param name="CarState">状态字段</param>
        /// <returns></returns>
        [Route("api/ChangeState")]
        [HttpGet]
        public int ChangeState(int cid, int CarState)
        {
    
    
            //通过id找到数据
            var obj = Car.Query().Find(cid);
            //更新状态值
            obj.CarState = CarState;
            //执行修改保存,将状态保存至数据库更新数据
            return Car.Edit(obj);
        }

/// <summary>
        /// 导出数据 Excel表格
        /// </summary>
        [Route("api/DaoChu")]
        [HttpGet]
        public void ToExcel()
        {
    
    
            //获取数据
            var list = Car.Query();
            //转json字符串
            var json = JsonConvert.SerializeObject(list);
            //转 datatable类型 
            DataTable dt = new DataTable();
            dt = JsonConvert.DeserializeObject<DataTable>(json);
            //导出 ExcelHelper为封装好的帮助类 
            ExcelHelper.ExportByWeb(dt,"汽车产品","汽车.xls");
        }

	*********************以上后台基本完成***********************************

  
  

The front desk is simply html+js. If you
need it, you can take a look.
Shop display
Show shop
code Shop
Car display with paging
Car paging display
car code paging control address: http://www.jq22.com/jquery-info21889
Insert picture description here
Insert picture description here
add
Insert picture description here
delete modify status codeInsert picture description here

Export
Some of them are shown below 内联代码片.

function toExcel() {
    
    
        location.href = "http://localhost:57536/api/DaoChu";
    }

A simple EF addition, deletion, modification, and checking is complete! ! !

Guess you like

Origin blog.csdn.net/d1332508051/article/details/107303793