Generic method to retrieve DbSet from DbContext

前端 未结 5 1217
长情又很酷
长情又很酷 2021-01-04 03:02

I\'m using the Entity Framework with a large database (made up of more than 200 tables).

Trying to create a generic method that returns the DbSet

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 03:56

    I don't know how you have created your model, and thus how your entities look like. But, if it's Code First, the entity classes don't inherit from a common base class, so you cannot add a type constraint to your generic.

    I don't recommend using a base class to be able to specify a constraint. It's much better to do it using an interface. An empty interface will allow you to specify a constraint without having to change your classes at all.

    So, what you can do is define an interface like this:

    public interface IEntity {};
    

    And then:

    • implement it in all classes, which can be done in partial classes files, modifying a T4 template or in some other way depending on how your model looks like
    • use it to specify the generic type constrain with where IEntity

    This is the cleanest way to do it, without any interference to your classes.

提交回复
热议问题