EF是微軟推出的官方ORM框架,默認防注入能夠配合LINQ一塊兒使用,更方便開發人員。數據庫
首先經過SQLSERVER如今有的數據庫類生產EF框架
右鍵-》添加-》新建項,選擇AOD.NET實體數據模型,來自數據庫的Code FIrstide
完成添加後會生成多個文件,而且在你的項目的配置文件中有數據庫的連接字符串,下面文件中 「name=Test」,ui
Test就是鏈接字符串的namespa
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; } }
實際使用code
BaseDB<Student> baseDB = new BaseDB<Student>(); baseDB.AddEntity(new Student { StudentId = Guid.NewGuid().ToString(), Name = "小紅" });