BaseService.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using YLShipBuildLandMap.Entity;
  5. namespace YLShipBuildLandMap.Services.Common
  6. {
  7. public class BaseService<TEntity> where TEntity : class
  8. {
  9. protected YLShipBuildLandMapContext DbContext { get; set; }
  10. public BaseService(YLShipBuildLandMapContext dbContext)
  11. {
  12. DbContext = dbContext;
  13. }
  14. public virtual TEntity Get(object keyValue)
  15. {
  16. return this.DbContext.Find<TEntity>(new object[] { keyValue });
  17. }
  18. public virtual int Delete(Expression<Func<TEntity, bool>> predicate)
  19. {
  20. this.DbContext.Set<TEntity>().Where(predicate).DeleteFromQuery();
  21. return this.DbContext.SaveChanges();
  22. }
  23. public virtual int Update(object keyValue, Func<TEntity, TEntity> updateFunc)
  24. {
  25. var entity = this.Get(keyValue);
  26. if (entity == null)
  27. {
  28. this.DbContext.Add<TEntity>(updateFunc(entity));
  29. }
  30. else
  31. {
  32. this.DbContext.Update<TEntity>(updateFunc(entity));
  33. };
  34. return this.DbContext.SaveChanges();
  35. }
  36. public virtual int UpdateFromQuery(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> updateFunc)
  37. {
  38. this.DbContext.Set<TEntity>().Where(predicate).UpdateFromQuery(updateFunc);
  39. return this.DbContext.SaveChanges();
  40. }
  41. }
  42. }