using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using RIZO.Server.IService; using RIZO.Server.IEFContext; namespace RIZO.Server.Service { public class ServiceBase : IServiceBase { protected DbContext Context { get; private set; } public ServiceBase(RIZO.Server.IEFContext.IEFContext eFContext) { Context = eFContext.CreateDBContext(); } public void Commit() { this.Context.SaveChanges(); } public void Delete(int Id) where T : class { T t = this.Find(Id);//也可以附加 if (t == null) throw new Exception("t is null"); this.Context.Set().Remove(t); this.Commit(); } public void Delete(T t) where T : class { if (t == null) throw new Exception("t is null"); this.Context.Set().Attach(t); this.Context.Set().Remove(t); this.Commit(); } public void Delete(IEnumerable tList) where T : class { foreach (var t in tList) { this.Context.Set().Attach(t); } this.Context.Set().RemoveRange(tList); this.Commit(); } public T Find(int id) where T : class { return this.Context.Set().Find(id); } public T Insert(T t) where T : class { this.Context.Set().Add(t); this.Commit(); return t; } public IEnumerable Insert(IEnumerable tList) where T : class { this.Context.Set().AddRange(tList); this.Commit();//写在这里 就不需要单独commit 不写就需要 return tList; } public IQueryable Query(Expression> funcWhere) where T : class { return this.Context.Set().Where(funcWhere); } public void Update(T t) where T : class { if (t == null) throw new Exception("t is null"); this.Context.Set().Attach(t);//将数据附加到上下文,支持实体修改和新实体,重置为UnChanged this.Context.Entry(t).State = EntityState.Modified; this.Commit(); } public void Update(IEnumerable tList) where T : class { foreach (var t in tList) { this.Context.Set().Attach(t); this.Context.Entry(t).State = EntityState.Modified; } this.Commit(); } public virtual void Dispose() { if (this.Context != null) { this.Context.Dispose(); } } } }