Generic class with Id c#

后端 未结 2 1254
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 05:39

I am not sure if this is possible, but I have started a new project and I am trying to clean up the way I work with the DbContext. I am trying to do this by

2条回答
  •  星月不相逢
    2021-01-15 06:00

    you can have your entities like this :

    public interface IEntity
    {
        TKey Id { get; }
    }
    
    public class Question : IEntity
    {
         public TPrimaryKey Id { get; set; }
    }
    

    then your repository like this :

    public class Repository where TEntity: IEntity
    {
        protected readonly DbContext _dbContext;
        protected readonly DbSet _dbEntitySet;
    
        public Repository(InteractiveChoicesContext dbContext)
        {
            _dbContext = dbContext;
            _dbEntitySet = dbContext.Set();
        }
    }
    

    and in my opinion, this is the best way to do it "Generic".

提交回复
热议问题