.net core Repository (学习笔记7)


1、接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace WebApplication29
{
    public interface IRepository<T> where T : class
    {
        IQueryable<T> GetAll();

        T Add(T entity);

        T Update(T entity);

        T Find(int Id);

    }
}

2、实现

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace WebApplication29
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly AppDbContext _appDbContext;

        private DbSet<T> _entity;
        public Repository(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
          
        }

        private DbSet<T> Entity => _entity ?? (_entity = _appDbContext.Set<T>());

        public T Add(T entity)
        {
            Entity.Add(entity);
           _appDbContext.SaveChanges();
            return entity;
        }

        public T Find(int Id)
        {
            return Entity.Find(Id);
        }

        public IQueryable<T> GetAll()
        {
            return Entity.AsQueryable().AsNoTracking();
        }

        public T Update(T entity)
        {
            Entity.Update(entity);
            _appDbContext.SaveChanges();
            return entity;
        }
    }
}

3、startup服务绑定

 

 4、 注入

 

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM