标签:ram order 实体 orderby 分页 rtu update index stat
EF是微软推出的官方ORM框架,默认防注入可以配合LINQ一起使用,更方便开发人员。
首先通过SQLSERVER现在有的数据库类生产EF
右键-》添加-》新建项,选择AOD.NET实体数据模型,来自数据库的Code FIrst
完成添加后会生成多个文件,并且在你的项目的配置文件中有数据库的链接字符串,下面文件中 “name=Test”,
Test就是连接字符串的name
public partial class TestDB : DbContext { public TestDB() : base("name=Test") { }
public virtual DbSet<School> School { get; set; } public virtual DbSet<Student> Student { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { }
public partial class School { [StringLength(50)] public string SchoolId { get; set; } [StringLength(50)] public string Name { get; set; } public DateTime? CreateTime { get; set; } [StringLength(100)] public string Address { get; set; } [StringLength(50)] public string Telephone { get; set; } }
public partial class Student { [StringLength(50)] public string StudentId { get; set; } [StringLength(50)] public string Name { get; set; } }
School和Student就是根据数据库表来生成的类
通过泛型来做基础操作
class BaseDB<T> where T : class, new() { DbContext Db = new Test(); //查询 public IQueryable<T> LaodEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { return Db.Set<T>().Where<T>(whereLambda); } //更新 public bool EditEntity(T entity) { Db.Entry<T>(entity).State = EntityState.Modified; return Db.SaveChanges() > 0; } //添加 public bool AddEntity(T entity) { Db.Set<T>().Add(entity); return Db.SaveChanges() > 0; } //删除 public bool DeleteEntity(T entity) { Db.Entry<T>(entity).State = EntityState.Deleted; return Db.SaveChanges() > 0; } //批量添加 public bool AddBatch(IList<T> arrObj) { Db.Set<T>().AddRange(arrObj); return Db.SaveChanges() > 0; } //批量更改 public bool UpdateBatch(IList<T> arrObj) { foreach (var item in arrObj) { Db.Entry<T>(item).State = EntityState.Modified; } return Db.SaveChanges() > 0; } //批量删除 public bool DeleteBatch(IList<T> arrObj) { foreach (var item in arrObj) { Db.Entry<T>(item).State = EntityState.Deleted; } return Db.SaveChanges() > 0; } //分页 public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc) { var temp = Db.Set<T>().Where<T>(whereLambda); totalCount = temp.Count(); if (isAsc)//升序 { temp = temp.OrderBy<T, s>(orderbyLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize); } else { temp = temp.OrderByDescending<T, s>(orderbyLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize); } return temp; } }
实际使用
BaseDB<Student> baseDB = new BaseDB<Student>(); baseDB.AddEntity(new Student { StudentId = Guid.NewGuid().ToString(), Name = "小红" });
标签:ram order 实体 orderby 分页 rtu update index stat
原文地址:https://www.cnblogs.com/VvVvLJS/p/11123566.html