首页 > Web开发 > 详细

.net core Repository (学习笔记7)

时间:2020-01-03 17:36:28      阅读:247      评论:0      收藏:0      [点我收藏+]

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

技术分享图片

 

 

  

.net core Repository (学习笔记7)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!