.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