Generic method to retrieve DbSet from DbContext

前端 未结 5 1259
长情又很酷
长情又很酷 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 04:01

    Issue

    I suppose your TableA class doesn't implement EntityObject. That's why you're getting this error. To solve this you can have an abstract class/interface which will be base for all context entities (i.e. IContextEntity which will have unique Id definition):

    public class TableA : IContextEntity
    {
       ...
    }
    

    Then same method but with new interface instead of EntityObject and you can mock/test it easily

    public IQueryable GetFromDatabase() where T : IContextEntity
    {
         ...
    }
    


    Usage(Tests)

    Second important thing is the way you want to use this method. In case of Entity Framework context it is really important to have separation between integration and unit tests. In code you provided you're trying to reach database which means that this test will be integration:

    using (sqlEntities ctx = new sqlEntities()) // This will open a DB connection
    

    Connecting to a databases or external sources is usually a bad practice unless you know what you do and this is exactly it. If you just need some fake/dummy data to perform an action on it - use Stubs.

提交回复
热议问题