Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. EF Core 6 Repository Pattern

EF Core 6 Repository Pattern

Scheduled Pinned Locked Moved C#
databasecsharpasp-netlinqcom
6 Posts 2 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kevin Marois
    wrote on last edited by
    #1

    I have an old Linq-To-Sql DAL that I'm converting to a EF Core 6. I'm using the Repostory pattern. I've [looked at this article](https://code-maze.com/net-core-web-development-part4/) and others like it, and the all seem to do it the same way... Interface

    public interface IRepository<T> where T : class
    {
        void Add(T entity);
        void AddRange(IEnumerable<T> entities);
        void Delete(T entity);
        void DeleteRange(IEnumerable<T> entities);
        T Get(int id);
        IEnumerable<T> Get(Expression<Func<T, bool>> expression);
        IEnumerable<T> GetAll();
    }
    

    Base Repository

    public class BaseRepository<T> : IRepository<T> where T : class
    {
    protected readonly DbContext _context;

    public BaseRepository(DbContext context)
    {
        \_context = context;
    }
    
    // Interface methods here
    

    }

    Customer Repository

    public class CustomerRepository : BaseRepository<CustomerEntity>, ICustomerRepository
    {
    public CustomerRepository(DbContext context)
    :base(context)
    {
    }

    public bool IsCustomerActive(int id)
    {
        return true;
    }
    

    }

    Usage

    public class CustomerController : ControllerBase
    {
    public bool CheckIfCustomerIsActive(int id)
    {
    var connString = "";

        var dc = new SqlDataContext(connString);
            
        ICustomerRepository repository = new CustomerRepository(dc);
    
        return repository.IsCustomerActive(id);
    }
    

    }

    Issues I See Everything about this seems clean and maintainable, except 1. The Connnection String is in the controller. I see this in a lot of examples. 2. By design, the controller must create and pass the data context to the repos. It seems to me that these 2 issues create a tight coupling between the API and the DAL.Why would a controller ever need to know the conn string OR DBContext? Those are both specific to the DAL. Why not do this instead?

    public class BaseRepository<T> : IRepository<T> where T : class
    {
    protected readonly DbContext _context;

    public BaseRepository()
    {
        // The base repo is the only place that gets the connection string
        var connString = Properties.Settings.Default.ConnectionString;
    
        // The base repo is the only place that knows about the db context
        \_context = new SqlData
    
    Richard DeemingR 1 Reply Last reply
    0
    • K Kevin Marois

      I have an old Linq-To-Sql DAL that I'm converting to a EF Core 6. I'm using the Repostory pattern. I've [looked at this article](https://code-maze.com/net-core-web-development-part4/) and others like it, and the all seem to do it the same way... Interface

      public interface IRepository<T> where T : class
      {
          void Add(T entity);
          void AddRange(IEnumerable<T> entities);
          void Delete(T entity);
          void DeleteRange(IEnumerable<T> entities);
          T Get(int id);
          IEnumerable<T> Get(Expression<Func<T, bool>> expression);
          IEnumerable<T> GetAll();
      }
      

      Base Repository

      public class BaseRepository<T> : IRepository<T> where T : class
      {
      protected readonly DbContext _context;

      public BaseRepository(DbContext context)
      {
          \_context = context;
      }
      
      // Interface methods here
      

      }

      Customer Repository

      public class CustomerRepository : BaseRepository<CustomerEntity>, ICustomerRepository
      {
      public CustomerRepository(DbContext context)
      :base(context)
      {
      }

      public bool IsCustomerActive(int id)
      {
          return true;
      }
      

      }

      Usage

      public class CustomerController : ControllerBase
      {
      public bool CheckIfCustomerIsActive(int id)
      {
      var connString = "";

          var dc = new SqlDataContext(connString);
              
          ICustomerRepository repository = new CustomerRepository(dc);
      
          return repository.IsCustomerActive(id);
      }
      

      }

      Issues I See Everything about this seems clean and maintainable, except 1. The Connnection String is in the controller. I see this in a lot of examples. 2. By design, the controller must create and pass the data context to the repos. It seems to me that these 2 issues create a tight coupling between the API and the DAL.Why would a controller ever need to know the conn string OR DBContext? Those are both specific to the DAL. Why not do this instead?

      public class BaseRepository<T> : IRepository<T> where T : class
      {
      protected readonly DbContext _context;

      public BaseRepository()
      {
          // The base repo is the only place that gets the connection string
          var connString = Properties.Settings.Default.ConnectionString;
      
          // The base repo is the only place that knows about the db context
          \_context = new SqlData
      
      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      Are you using Dependency Injection? Ideally, the DbContext and repository classes should be registered as "scoped" dependencies. The context would be injected into the repository, and the repository would be injected into the controller. The connection string would usually be read from the web.config / appSettings.json file by convention: Connection strings and models - EF6 | Microsoft Learn[^] If you need to manage the connection string differently, then you should be able to add it to the DI registration. For example, using the Microsoft DI framework:

      services.AddScoped<DbContext>(_ =>
      {
      string connString = Properties.Settings.Default.ConnectionString;
      return new SqlDataContext(connString);
      });


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      K 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        Are you using Dependency Injection? Ideally, the DbContext and repository classes should be registered as "scoped" dependencies. The context would be injected into the repository, and the repository would be injected into the controller. The connection string would usually be read from the web.config / appSettings.json file by convention: Connection strings and models - EF6 | Microsoft Learn[^] If you need to manage the connection string differently, then you should be able to add it to the DI registration. For example, using the Microsoft DI framework:

        services.AddScoped<DbContext>(_ =>
        {
        string connString = Properties.Settings.Default.ConnectionString;
        return new SqlDataContext(connString);
        });


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        K Offline
        K Offline
        Kevin Marois
        wrote on last edited by
        #3

        Richard Deeming wrote:

        Are you using Dependency Injection? Ideally, the DbContext and repository classes should be registered as "scoped" dependencies. The context would be injected into the repository, and the repository would be injected into the controller.

        Yes, that's exactly what I was thinking. Many of the examples you find out there show the DbContext referenced in the controller.

        Richard Deeming wrote:

        f you need to manage the connection string differently,

        It seems to me that the ConnectionString belongs in the Repository project. The Controller get the repo, and the repo knows how to contact the DB. Thanks

        If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

        Richard DeemingR 1 Reply Last reply
        0
        • K Kevin Marois

          Richard Deeming wrote:

          Are you using Dependency Injection? Ideally, the DbContext and repository classes should be registered as "scoped" dependencies. The context would be injected into the repository, and the repository would be injected into the controller.

          Yes, that's exactly what I was thinking. Many of the examples you find out there show the DbContext referenced in the controller.

          Richard Deeming wrote:

          f you need to manage the connection string differently,

          It seems to me that the ConnectionString belongs in the Repository project. The Controller get the repo, and the repo knows how to contact the DB. Thanks

          If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          Kevin Marois wrote:

          It seems to me that the ConnectionString belongs in the Repository project.

          The connection string shouldn't be hard-coded anywhere. It belongs in the configuration settings of the application - in this case, the web site. For .NET Framework, that would usually be the <connectionStrings> section of the web.config or YourApp.exe.config file. For .NET Core/5/6/7/..., that usually would be the "ConnectionStrings" section of the appSettings.json file, although you could use any custom section you want. The .NET configuration system is much more flexible, so you could also choose to store the connection string in any of the configuration sources your application uses - environment variables, Azure secrets, etc.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          K 1 Reply Last reply
          0
          • Richard DeemingR Richard Deeming

            Kevin Marois wrote:

            It seems to me that the ConnectionString belongs in the Repository project.

            The connection string shouldn't be hard-coded anywhere. It belongs in the configuration settings of the application - in this case, the web site. For .NET Framework, that would usually be the <connectionStrings> section of the web.config or YourApp.exe.config file. For .NET Core/5/6/7/..., that usually would be the "ConnectionStrings" section of the appSettings.json file, although you could use any custom section you want. The .NET configuration system is much more flexible, so you could also choose to store the connection string in any of the configuration sources your application uses - environment variables, Azure secrets, etc.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            K Offline
            K Offline
            Kevin Marois
            wrote on last edited by
            #5

            Richard Deeming wrote:

            The connection string shouldn't be hard-coded anywhere. It belongs in the configuration settings of the application - in this case, the web site.

            I never said hard coded. I said it belongs in the Repository project, in the app.config for THAT project. Why would the web site nedd to know it? As far as the web site knows, it simply gets a repo injected into it. The Repo gets the connstring from its app.config. This was my question all along. I don't get why the controller knows anything about the DB.

            If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

            Richard DeemingR 1 Reply Last reply
            0
            • K Kevin Marois

              Richard Deeming wrote:

              The connection string shouldn't be hard-coded anywhere. It belongs in the configuration settings of the application - in this case, the web site.

              I never said hard coded. I said it belongs in the Repository project, in the app.config for THAT project. Why would the web site nedd to know it? As far as the web site knows, it simply gets a repo injected into it. The Repo gets the connstring from its app.config. This was my question all along. I don't get why the controller knows anything about the DB.

              If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #6

              Class libraries don't have a separate configuration file. They get their configuration from the application that uses them - in this case, the web site.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups