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

原文:https://www.cnblogs.com/stonechina/p/12145434.html