使用具有不同 ID 名称的通用存储库

问题描述 投票:0回答:0

目标:
当您的表 ID 名称不同时,请使用通用存储库。不同的名称例如“TTest1Id”、“TTest2id”等。它不是“Id”的名称。

问题:
当我使用与表的 ID 名称 ID 相关的通用存储库时,它有效。

我应该如何使用与不同 ID 名称(在每个表中)相关的通用存储库,例如“TTest1Id”、“TTest2id”等?

谢谢!


namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private SakuraContext _db;
        private readonly IGenericRepositoryCommand<Ttest1> _repositoryTtest1 = null;
        private readonly IGenericRepositoryCommand<Ttest2> _repositoryTtest2 = null;

        public WeatherForecastController(
            JanaruContext db,
            IGenericRepositoryCommand<Ttest1> repositoryTtest1,
            IGenericRepositoryCommand<Ttest2> repositoryTtest2)
        {
            this._db = db;
            this._repositoryTtest1 = repositoryTtest1;
            this._repositoryTtest2 = repositoryTtest2;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            var test = _repositoryTtest1.GetById(1);

            return null;
        }
    }
}

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

namespace ConsoleApp1.Data
{
    public interface IGenericRepositoryCommand<T> where T : class
    {
        public IQueryable<T> GetAll();
        Task<ICollection<T>> GetAllAsync();



        IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
        Task<ICollection<T>> FindByAsync(Expression<Func<T, bool>> predicate);
        T GetById(int id);
        Task<T> GetAsync(int id);



        Task AddAsync(T obj, bool detachAllAfterSave = false);
        Task UpdateAsync(T obj);
        Task DeleteAsync(T entity);



        T Add(T t, bool detachAllAfterSave = false);
        T Update(T t, object key);
        void Delete(T entity);



        void AddRange(IEnumerable<T> entities);
        void RemoveRange(IEnumerable<T> entities);



        Task AddRangeAsync(IEnumerable<T> entities);
    }


    public class GenericRepositoryCommand<T> : IGenericRepositoryCommand<T> where T : class
    {
        private readonly SakuraContext _context = null;

        /*
        public GenericRepositoryCommand()
        {
            this._context = new TableContext();
            table = _context.Set<T>();
        }
        */

        public GenericRepositoryCommand(SakuraContext context)
        {
            this._context = context;
        }


        public IQueryable<T> GetAll()
        {
            return this._context.Set<T>();
        }


        public async Task<ICollection<T>> GetAllAsync()
        {
            return await _context.Set<T>().ToListAsync();
        }


        public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = _context.Set<T>().Where(predicate);
            return query;
        }


        public virtual async Task<ICollection<T>> FindByAsync(Expression<Func<T, bool>> predicate)
        {
            return await _context.Set<T>().Where(predicate).ToListAsync();
        }


        public T GetById(int id)
        {
            return this._context.Set<T>().Find(id);
        }


        public async Task<T> GetAsync(int id)
        {
            return await _context.Set<T>().FindAsync(id);
        }


        public async Task AddAsync(T entity, bool detachAllAfterSave = false)
        {
            if (entity == null)
            {
                throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
            }

            try
            {
                await _context.AddAsync(entity);
                await _context.SaveChangesAsync();

                if (detachAllAfterSave)
                    DetachAll();
            }
            catch (Exception)
            {
                throw new Exception($"{nameof(entity)} could not be saved");
            }
        }


        public async Task UpdateAsync(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException($"{nameof(UpdateAsync)} entity must not be null");
            }

            try
            {
                _context.Update(entity);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception($"{nameof(entity)} could not be updated");
            }
        }


        public async Task DeleteAsync(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException($"{nameof(DeleteAsync)} entity must not be null");
            }

            try
            {
                _context.Remove(entity);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception($"{nameof(entity)} could not be updated");
            }
        }


        public T Add(T t, bool detachAllAfterSave = false)
        {
            var addedEntity = _context.Set<T>().Add(t);
            _context.SaveChanges();

            if (detachAllAfterSave)
                DetachAll();

            return addedEntity.Entity;
        }


        public T Update(T t, object key)
        {
            if (t == null)
                return null;

            T exist = _context.Set<T>().Find(key);

            if (exist != null)
            {
                _context.Entry(exist).CurrentValues.SetValues(t);
                _context.SaveChanges();
            }
            return exist;
        }


        public void Delete(T entity)
        {
            _context.Set<T>().Remove(entity);
            _context.SaveChanges();
        }


        public void AddRange(IEnumerable<T> entities)
        {
            _context.Set<T>().AddRange(entities);
        }


        public void RemoveRange(IEnumerable<T> entities)
        {
            _context.Set<T>().RemoveRange(entities);
        }


        public async Task AddRangeAsync(IEnumerable<T> entities)
        {
            if (entities == null)
            {
                throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
            }

            try
            {
                await _context.Set<T>().AddRangeAsync(entities);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception($"{nameof(entities)} could not be saved");
            }
        }


        private void DetachAll()
        {
            foreach (var entityEntry in _context.ChangeTracker.Entries().ToArray())
            {
                entityEntry.State = EntityState.Detached;
            }
        }
    }
}

CREATE TABLE [dbo].[TTest1](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [isbn] [varchar](50) NOT NULL,
    [date] [datetime] NOT NULL,
    [score] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO


CREATE TABLE [dbo].[TTest2](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [isbn] [varchar](50) NOT NULL,
    [date] [datetime] NOT NULL,
    [score] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

c# generics repository .net-6.0 ef-core-6.0
© www.soinside.com 2019 - 2024. All rights reserved.