.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、 注入

 

 

  

posted @ 2020-01-03 16:08  面无表情的石头  阅读(1072)  评论(0)    收藏  举报