• C# 基于ef的2种简单的仓储封装和工作单元 net core3.1 ---sqlserver 2019


    1配置

     1         public void ConfigureServices(IServiceCollection services)
     2         {
     3             services.AddControllers();
     4             services.AddCors();
     5 
     6             services.AddDbContext<MyDbContext>(option =>
     7             {
     8                 option.UseSqlServer(Configuration.GetConnectionString("connection"));
     9             });
    10 
    11             //<IRepository<>, Repository<>>
    12             // 泛型注入
    13             services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    14             // 非泛型注入
    15             services.AddScoped<IRepository, Repository>();
    16 
    17             //注入工作单元
    18             services.AddScoped<IunitOfWork, UnitOfWork>();
    19 
    20         }
     1   public class MyDbContext : DbContext
     2     {
     3 
     4         public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
     5         {
     6           
     7         }
     8 
     9         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    10         {
    11             optionsBuilder.Options.Extensions.LastOrDefault();
    12 
    13             //.UseSqlServer(Configuration.GetConnectionString("connection")
    14             //optionsBuilder.UseSqlServer("Data Source=blog.db");
    15         }
    16 
    17         /// <summary>
    18         /// OnModelCreating
    19         /// </summary>
    20         /// <param name="modelBuilder"></param>
    21         protected override void OnModelCreating(ModelBuilder modelBuilder)
    22         {
    23             base.OnModelCreating(modelBuilder);
    24         }
    25 
    26         public DbSet<MessageMode> MessageMode { get; set; }
    27 
    28     }

    2.第一种实现

    接口

     1 public interface IRepository
     2 {
     3 
     4   IEnumerable<T> GetConditions<T>(Func<T, bool> predicate = null) where T : class;
     5 
     6   T Get<T>(Func<T, bool> predicate) where T : class;
     7 
     8   T Get<T>(params object[] keyValues) where T : class;
     9 
    10   void Add<T>(T entity);
    11 
    12   void AddRange<T>(List<T> entitys);
    13 
    14   void Update<T>(T entity);
    15 
    16   void Delete<T>(T entity);
    17 
    18   void Delete<T>(List<T> entitys);
    19 
    20 }

    实现

     1 public class Repository : IRepository
     2 {
     3 
     4    private MyDbContext dbContext;
     5 
     6   /// <summary>
     7   /// 构造函数注入
     8   /// </summary>
     9   /// <param name="_dbContext"></param>
    10   public Repository(MyDbContext _dbContext)
    11   {
    12     dbContext = _dbContext;
    13   }
    14 
    15   public void Add<T>(T entity)
    16   {
    17     dbContext.Add(entity);
    18   }
    19 
    20   public void AddRange<T>(List<T> entitys)
    21   {
    22     dbContext.AddRange(entitys);
    23   }
    24 
    25   public void Update<T>(T entity)
    26   {
    27     dbContext.Update(entity);
    28   }
    29 
    30   public void Delete<T>(T entity)
    31   {
    32     dbContext.Remove(entity);
    33   }
    34 
    35   public void Delete<T>(List<T> entitys)
    36   {
    37     dbContext.RemoveRange(entitys);
    38   }
    39 
    40   public T Get<T>(Func<T, bool> predicate) where T : class
    41   {
    42     return dbContext.Set<T>().Where(predicate).FirstOrDefault();
    43   }
    44 
    45   public T Get<T>(params object[] keyValues) where T : class
    46   {
    47     return dbContext.Find<T>(keyValues);
    48   }
    49 
    50   public IEnumerable<T> GetConditions<T>(Func<T, bool> predicate = null) where T : class
    51   {
    52     if (predicate == null)
    53     {
    54       return dbContext.Set<T>().Where(l => true);
    55     }
    56     return dbContext.Set<T>().Where(predicate);
    57   }
    58 }

    3.第二种实现

    接口

    public interface IRepository<T> where T : class
    {
      IEnumerable<T> GetConditions(Func<T, bool> predicate = null);

      T Get(Func<T, bool> predicate);

      T Get(params object[] keyValues);

      void Add(T entity);

      void AddRange(List<T> entitys);

      void Update(T entity);

      void Delete(T entity);

      void Delete(List<T> entitys);

    }

    实现

    public class Repository<T> : IRepository<T> where T : class
    {

      private MyDbContext dbContext ;

      public MyDbContext Context => dbContext;

      /// <summary>
      /// 构造函数注入
      /// </summary>
      /// <param name="_dbContext"></param>
      public Repository(MyDbContext _dbContext)
      {
        dbContext = _dbContext;
      }

      public void Add(T entity)
      {
        dbContext.Add(entity);
      }

      public void AddRange(List<T> entitys)
      {
        dbContext.AddRange(entitys);
      }

      public void Update(T entity)
      {
        dbContext.Update(entity);
      }

      public void Delete(T entity)
      {
        //dbContext.Add(entity).State = EntityState.Deleted;
        dbContext.Remove(entity);
      }

      public void Delete(List<T> entitys)
      {
        //dbContext.Add(entity).State = EntityState.Deleted;
        dbContext.RemoveRange(entitys);
      }

      public T Get(Func<T, bool> predicate)
      {
        return dbContext.Set<T>().Where(predicate).FirstOrDefault();
      }

      public T Get(params object[] keyValues)
      {
        return dbContext.Find<T>(keyValues);
      }

      public IEnumerable<T> GetConditions(Func<T, bool> predicate = null)
      {
        if (predicate == null)
        {
          return dbContext.Set<T>().Where(l=>true);
        }
        return dbContext.Set<T>().Where(predicate);
      }
    }

     工作单元

    接口

        public interface IunitOfWork
        {
            void Commit();
        }

    实现

        public class UnitOfWork : IunitOfWork
        {
            private MyDbContext _dbContext;
            public UnitOfWork(MyDbContext dbContext)
            {
                _dbContext = dbContext;
            }
    
            public void Commit()
            {
                _dbContext.SaveChanges();
            }
        }

    最终再给一个使用的例子,

        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
           
            private readonly ILogger<WeatherForecastController> _logger;
            private readonly IRepository<MessageMode> _userRepository;
            private readonly IRepository _repository;
            private readonly IunitOfWork _IunitOfWork;
            public WeatherForecastController(ILogger<WeatherForecastController> logger,
                IRepository<MessageMode> userRepository,
                IRepository repository, IunitOfWork IunitOfWork)
            {
                _logger = logger;
                _userRepository = userRepository;
                _repository = repository;
                _IunitOfWork = IunitOfWork;
            }
    
            
            [HttpGet]
            public IEnumerable<MessageDto> Get()
            {
                return _repository.GetConditions<MessageMode>().Adapt<List<MessageDto>>();
            }
    
            [HttpPost]
            public IActionResult Post(MessageDto messageDto)
            {
                var model = messageDto.Adapt<MessageMode>();
         
                _repository.Add<MessageMode>(model);
                _IunitOfWork.Commit();
                return Ok("ok");
            }
    
    
        }
    过去的永远过去,未来的一直在等待.
  • 相关阅读:
    Word pair Hu
    [bzoj1601] 灌水
    小木棍
    雇佣计划
    [Luogu1282] 多米诺骨牌
    [Luogu1216] 数字三角形
    [Luogu1734] 最大约数和
    [NOIp2008] 传纸条
    [Luogu1325] 雷达安装
    nginx
  • 原文地址:https://www.cnblogs.com/hkyyqqq/p/15030272.html
Copyright © 2020-2023  润新知