avatarLarry Schoeneman

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3008

Abstract

d="9d55">So, first, lets create our dbContext class</p><div id="a898"><pre><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SampleDbContext</span> : <span class="hljs-type">DbContext</span> { <span class="hljs-keyword">public</span> DbQuery<SampleEntity> SampleEntities {<span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>;} } </pre></div><p id="af74">Here is where things get a little different. Instead of passing in a connection string, or just using a default, we will pass in an instance of DbContextOptions, which of course, we will pass in via dependency injection. We will tell the contextOptions object what connection string to use.</p><p id="3d4c">When we pass in the DbContextOptions instance, we need to pass this along to the base class. So our constructor might look like:</p><div id="d4fe"><pre><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IConfiguration _configuration;</pre></div><div id="9b57"><pre><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SampleDbContext</span><span class="hljs-params">(IConfiguration configuration,
ILogger<SampleDbContext> logger, DbContextOptions dbContextOptions)</span>:base(dbContextOptions) {</span> _configuration = configuration;
}</pre></div><p id="10a9">As mentioned, we pass the dbContextOptions object along to the base class (DbContext) where it is kind enough to set up our connection for us.</p><p id="74a0">Next, we open our favorite Program.cs file and update our ConfigureServices method to properly inject our database connection string. It will look like:</p><div id="e211"><pre>private static IServiceCollection ConfigureServices() { IServiceCollection services <span class="hljs-operator">=</span> new ServiceCollection()<span class="hljs-comment">;</span> var config <span class="hljs-operator">=</span> LoadConfiguration()<span class="hljs-comment">;</span> services.AddLogging(logging <span class="hljs-operator">=</span>>{ logging.AddConfiguration(config.GetSection(<span class="hljs-string">"Logging"</span>))<span class="hljs-comment">;</span> logging.AddConsole()<span class="hljs-comment">;</span> }).Configure<LoggerFilterOptions>(options<span class="hljs-operator">=</span>>options.MinLevel <span class="hljs-operator">=</span>
LogLevel.Information)<span class="hljs-comment">;</span></pre></div><div id="6de7"><pre> services.AddSingleton(config)<span class="hljs-comment">;</span></pre></div><div id="7a21"><pre> services.AddTransient<span class="hljs-attribute"><ITestService, TestService></span>();</pre></div><div id="1919"><pre> // <span class="hljs-keyword">Set</span> up our <span class="hljs-keyword">database</span> <span class="hljs-keyword">by</span> adding the dbcontext <span cla

Options

ss="hljs-keyword">to</span> our services // collection. <span class="hljs-keyword">Then</span> <span class="hljs-keyword">set</span> up our <span class="hljs-keyword">options</span> <span class="hljs-keyword">object</span> <span class="hljs-keyword">for</span> injection </pre></div><div id="e952"><pre> services.AddDbContext<SampleDbContext> (opts<span class="hljs-operator">=</span>>opts.UseSqlServer(config.GetConnectionString(<span class="hljs-string">"Storage"</span>)))<span class="hljs-comment">;</span></pre></div><div id="4e46"><pre> services.AddTransient<ConsoleApplication>()<span class="hljs-comment">;</span> return services<span class="hljs-comment">;</span> }</pre></div><p id="438a">As noted, we add our context into the collection of DbContexts and we configure its options with a sql server connection string.</p><p id="479d">Now, finally, we are ready to use it! So, we will inject our database context into our service (probably want to use an actual repository for this, but this is just an example).</p><p id="a2a3">So we update our service constructor to look like:</p><div id="e28c"><pre><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TestService</span> : ITestService { <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger<TestService> _logger; <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> SampleDbContext _sampleDbContext;</pre></div><div id="2722"><pre> <span class="hljs-attribute">public</span> TestService(SampleDbContext dbContext, ILogger<TestService> logger) { <span class="hljs-attribute">_sampleDbContext</span> = dbContext; <span class="hljs-attribute">_logger</span> = logger; }</pre></div><div id="600f"><pre> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomethingUseful</span>()</span> { <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">from</span> s <span class="hljs-keyword">in</span> _sampleDbContext.SampleEntities <span class="hljs-keyword">where</span> s.Name = <span class="hljs-string">"...."</span> <span class="hljs-keyword">select</span> s;</pre></div><div id="6d41"><pre> } }</pre></div><p id="05cf">Boom! there you go! Database access in a dependency injected, logging, configurable console application using .Net Core 2.2.</p><p id="1049">Just a couple last points. If you are concerned about injecting the dbContext and not using the dispose pattern to get rid of it, don’t be. The call to AddDbContext in our ConfigureServices method will release it when its out of scope. So yay!</p><p id="a478">Anyway, that’s about all I have to say about console applications. Have fun and don’t do anything too crazy!</p></article></body>

How to take advantage of EntityFramework.Core in .net Core 2.2 console applications

This is related my prior article on dependency injection in .net core 2.2 console apps, configuration, and logging. I am assuming once again that you’ve read that before coming here. Otherwise this will make no sense.

In previous articles we established dependency injection and enabled use of configuration and logging. Now its time to put Entity Framework Core into the mix.

I am going to assume you have been following along and have built the application so far. If you have not, go back and do so, otherwise reading this will be a waste of time.

As always, we need to add a couple new NuGet packages to the mix. Also as always, if you don’t know how to do this, go away. Leave. Now.

Add the following packages to the ones we already have:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer

Now, just like any other time we connect to SQL Server, we need to specify our connection string. Add the following section to you appSettings.json file:

"ConnectionStrings": {  "Storage": "Server=...;" }

Obviously you will need to fill in the correct connection string.

Now we need to have some things to use when connecting to the database. We will need two things:

  1. Our entity
  2. Our database context

Entities

We need at least one entity, so we will add a very simple one:

public class SampleEntity
{
    public int Id {get; set;}
    public string Name {get; set;}
}

Database context

Our database context will look a lot like standard Entity Framework Context, but we will need to make a couple tweaks:

So, first, lets create our dbContext class

public class SampleDbContext : DbContext
{
    public DbQuery<SampleEntity> SampleEntities {get; set;}
}    

Here is where things get a little different. Instead of passing in a connection string, or just using a default, we will pass in an instance of DbContextOptions, which of course, we will pass in via dependency injection. We will tell the contextOptions object what connection string to use.

When we pass in the DbContextOptions instance, we need to pass this along to the base class. So our constructor might look like:

private readonly IConfiguration _configuration;
public SampleDbContext(IConfiguration configuration,     
                ILogger<SampleDbContext> logger, DbContextOptions 
                dbContextOptions):base(dbContextOptions)
{
    _configuration = configuration;   
}

As mentioned, we pass the dbContextOptions object along to the base class (DbContext) where it is kind enough to set up our connection for us.

Next, we open our favorite Program.cs file and update our ConfigureServices method to properly inject our database connection string. It will look like:

private static IServiceCollection ConfigureServices()
{
    IServiceCollection services = new ServiceCollection();
    var config = LoadConfiguration();
    services.AddLogging(logging =>{
       logging.AddConfiguration(config.GetSection("Logging"));
       logging.AddConsole();
    }).Configure<LoggerFilterOptions>(options=>options.MinLevel =  
                                       LogLevel.Information);
    services.AddSingleton(config);
    services.AddTransient<ITestService, TestService>();
     // Set up our database by adding the dbcontext to our services 
     // collection.  Then set up our options object for injection 
    services.AddDbContext<SampleDbContext> 
   (opts=>opts.UseSqlServer(config.GetConnectionString("Storage")));
   services.AddTransient<ConsoleApplication>();
   return services;
}

As noted, we add our context into the collection of DbContexts and we configure its options with a sql server connection string.

Now, finally, we are ready to use it! So, we will inject our database context into our service (probably want to use an actual repository for this, but this is just an example).

So we update our service constructor to look like:

public class TestService : ITestService
{
    private readonly ILogger<TestService> _logger;
    private readonly SampleDbContext _sampleDbContext;
    public TestService(SampleDbContext dbContext, 
                       ILogger<TestService> logger)
    {
         _sampleDbContext = dbContext;
         _logger = logger; 
    }
    public void DoSomethingUseful()
    {
       var result = from s in _sampleDbContext.SampleEntities
                    where s.Name = "...."
                    select s;
    }
}

Boom! there you go! Database access in a dependency injected, logging, configurable console application using .Net Core 2.2.

Just a couple last points. If you are concerned about injecting the dbContext and not using the dispose pattern to get rid of it, don’t be. The call to AddDbContext in our ConfigureServices method will release it when its out of scope. So yay!

Anyway, that’s about all I have to say about console applications. Have fun and don’t do anything too crazy!

Net Core
C Sharp Programming
Console Application
Dependency Injection
Entity Framework Core
Recommended from ReadMedium