|
@@ -0,0 +1,71 @@
|
|
|
+using Microsoft.EntityFrameworkCore;
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.ComponentModel.DataAnnotations;
|
|
|
+using System.Linq;
|
|
|
+using System.Linq.Expressions;
|
|
|
+using System.Text;
|
|
|
+using System.Threading.Tasks;
|
|
|
+
|
|
|
+namespace ERP.Framework.WebApi
|
|
|
+{
|
|
|
+ public class BaseRepository<T, TDbContext> where T : BaseEntity where TDbContext : DbContext
|
|
|
+ {
|
|
|
+ private TDbContext _context;
|
|
|
+
|
|
|
+ public BaseRepository(TDbContext context)
|
|
|
+ {
|
|
|
+ _context = context;
|
|
|
+ }
|
|
|
+
|
|
|
+ public T? FirstOrDefault(Expression<Func<T, bool>> exp = null)
|
|
|
+ {
|
|
|
+ return Filter(exp).FirstOrDefault();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void Add(T entity)
|
|
|
+ {
|
|
|
+ _context.Set<T>().Add(entity);
|
|
|
+ Save();
|
|
|
+ _context.Entry(entity).State = EntityState.Detached;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void Save()
|
|
|
+ {
|
|
|
+ try
|
|
|
+ {
|
|
|
+ var entities = _context.ChangeTracker.Entries()
|
|
|
+ .Where(e => e.State == EntityState.Added
|
|
|
+ || e.State == EntityState.Modified)
|
|
|
+ .Select(e => e.Entity);
|
|
|
+
|
|
|
+ foreach (var entity in entities)
|
|
|
+ {
|
|
|
+ var validationContext = new ValidationContext(entity);
|
|
|
+ Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
|
|
|
+ }
|
|
|
+
|
|
|
+ _context.SaveChanges();
|
|
|
+ }
|
|
|
+ catch (ValidationException exc)
|
|
|
+ {
|
|
|
+ // Todo 抛出异常
|
|
|
+ //Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}");
|
|
|
+ //throw (exc.InnerException as Exception ?? exc);
|
|
|
+ }
|
|
|
+ catch (Exception ex) //DbUpdateException
|
|
|
+ {
|
|
|
+ // Todo 抛出异常
|
|
|
+ //throw (ex.InnerException as Exception ?? ex);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private IQueryable<T> Filter(Expression<Func<T, bool>> exp)
|
|
|
+ {
|
|
|
+ var dbSet = _context.Set<T>().AsNoTracking().AsQueryable();
|
|
|
+ if (exp != null)
|
|
|
+ dbSet = dbSet.Where(exp);
|
|
|
+ return dbSet;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|