Generic class with Id c#

后端 未结 2 1253
爱一瞬间的悲伤
爱一瞬间的悲伤 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<out TKey>
    {
        TKey Id { get; }
    }
    
    public class Question<TPrimaryKey> : IEntity<int>
    {
         public TPrimaryKey Id { get; set; }
    }
    

    then your repository like this :

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

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

    0 讨论(0)
  • 2021-01-15 06:08

    Well, you need some way to point towards the ID / key property.

    Some ideas to explore:

    • As you already wrote, create an interface which all your entities will implement which denotes the Id property
    • (Bonus) You can have a base entity class which implements the above interface AND has the required EF annotations ([DatabaseGenerated(DatabaseGeneratedOption.Identity)]) to make things easier
    • Use reflection to search for the Id property by name in your GetAsync method (obviously the code wouldn't be as simple as it is now)
    • Create a custom or use an existing attribute (for example, the KeyAttribute) and add it to your entities to mark the Id property and use reflection as with the idea before to find the property

    Of all of these solutions, I'd go for the first or second one as those seem to be most "clear". If you decide to go for reflection, then I'd go for the second one (where you have a key-defining attribute) - but this still forces you to go through all your entities and make changes. If you have a LOT of entities, then perhaps the text-based property search might be the fastest - but obviously any entity which doesn't have a property named "Id" will cause issues.

    Obviously YMMV depending on what you actually want to accomplish. Note that you can try and combine the reflection solutions (find by name, if not found search by key attribute).

    Also remember that while reflection is a powerful tool, it has a performance impact.

    0 讨论(0)
提交回复
热议问题