1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 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;
- }
- }
- }
|