EF是微軟推出的官方ORM框架,預設防註入可以配合LINQ一起使用,更方便開發人員。 首先通過SQLSERVER現在有的資料庫類生產EF 右鍵-》添加-》新建項,選擇AOD.NET實體數據模型,來自資料庫的Code FIrst 完成添加後會生成多個文件,並且在你的項目的配置文件中有資料庫的鏈接字元串 ...
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 = "小紅" });