<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>sql server &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>Help you to find best ASP.NET Core Hosting</description>
	<lastBuildDate>Fri, 06 Oct 2023 04:49:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>sql server &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Automate Bulk Data Import from MS Access to SQL Server</title>
		<link>https://topreviewhostingasp.net/how-to-automate-bulk-data-import-from-ms-access-to-sql-server/</link>
					<comments>https://topreviewhostingasp.net/how-to-automate-bulk-data-import-from-ms-access-to-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 06 Oct 2023 04:49:18 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[automate bulk data import]]></category>
		<category><![CDATA[bulk data import]]></category>
		<category><![CDATA[ms access]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql server tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3746</guid>

					<description><![CDATA[Data migration between databases is a regular task for database administrators. Bulk data import is useful for handling large amounts of data. It entails using a BCP utility, a SQL BULK INSERT statement, the command line, or SQL Server export/import tools like dbForge Data Pump to load data from a file into a SQL Server [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Data migration between databases is a regular task for database administrators. Bulk data import is useful for handling large amounts of data. It entails using a BCP utility, a SQL BULK INSERT statement, the command line, or SQL Server export/import tools like dbForge Data Pump to load data from a file into a SQL Server table.</p>
<p>In this article, we&#8217;ll look at how to use dbForge Data Pump and the PowerShell command line to bulk transfer data from MS Access tables to SQL Server.</p>
<p>Manual data entry may take a long time when moving large datasets. Instead, bulk data import is preferable because it minimizes the possibility of data entry errors while quickly transferring data between sources without requiring manual entry of every record.</p>
<p>To maintain regular data synchronization and keep data current, you can also automate and schedule bulk data import. You can transfer data between tables in a variety of formats using data import.</p>
<p>As you can see, using bulk data import has a lot of advantages. The BCP utility and a SQL Bulk Insert statement are where we begin our quick look at how it can be implemented.</p>
<p><img fetchpriority="high" decoding="async" class="wp-image-3747 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min.jpg" alt="" width="385" height="385" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min.jpg 2000w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-300x300.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-1024x1024.jpg 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-150x150.jpg 150w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-768x768.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-1536x1536.jpg 1536w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-50x50.jpg 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-70x70.jpg 70w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-127x127.jpg 127w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-476x476.jpg 476w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/sql-server-min-125x125.jpg 125w" sizes="(max-width: 385px) 100vw, 385px" /></p>
<h2 id="sql-bulk-insert-vs-bcp-utility" class="wp-block-heading">SQL BULK INSERT vs BCP utility</h2>
<p>Large amounts of data can be inserted from an external file into a SQL Server table or view using the BULK INSERT statement. It is appropriate for situations in which data loading effectiveness and efficiency are crucial.</p>
<p>The syntax of the claim is as follows:</p>
<pre class="lang:default decode:true ">BULK INSERT table_name
FROM 'path_to_file'
WITH (options);</pre>
<p>where:</p>
<ul>
<li><code class=" prettyprinted"><span class="pln">table_name</span></code> is the name of the table into which the data will be inserted. The name should be specified in the following format – <code class=" prettyprinted"><span class="pln">database_name</span><span class="pun">.</span><span class="pln">schema_name</span><span class="pun">.</span><span class="pln">table_name</span></code>.</li>
<li><code class=" prettyprinted"><span class="pln">path_to_file</span></code> is the full path to the file with the data you want to import.</li>
<li><code class=" prettyprinted"><span class="pln">options</span></code> are various options or configurations for the bulk insert operation.</li>
</ul>
<p>Using the bcp command-line tool is another well-liked method for bulk data import. Bulk Copy Program is known as BCP. Users can quickly import and export data from files into tables and views on SQL Server.</p>
<p>High-performance data transfer is the aim of BCP. It is frequently used for data migration, data warehousing, and ETL (Extract, Transform, Load) processes because it can effectively handle large datasets. To customize the import or export process to your needs, BCP lets you specify a variety of options, including data format, field and row terminators, and authentication details.</p>
<p>The following is an illustration of a BCP command that imports data from a CSV file into a SQL Server database table:</p>
<pre class="lang:default decode:true ">bcp MyDatabase.dbo.MyTable in datafile.csv -c -T ','</pre>
<p>where:</p>
<ul>
<li><code class=" prettyprinted"><span class="typ">MyDatabase</span><span class="pun">.</span><span class="pln">dbo</span><span class="pun">.</span><span class="typ">MyTable</span></code> is the target table into which data should be imported. In this illustration, data is being imported into the &#8220;MyTable&#8221; table, which is part of the &#8220;dbo&#8221; schema of the &#8220;MyDatabase.&#8221;</li>
<li><code class=" prettyprinted"><span class="kwd">in</span></code> identifies an import operation, or the copying of data from an external file into the specified table, as being in progress.</li>
<li><code class=" prettyprinted"><span class="pln">datafile</span><span class="pun">.</span><span class="pln">csv</span></code> is a CSV file that you want to import data from on the outside.</li>
<li><code class=" prettyprinted"><span class="pun">-</span><span class="pln">c</span></code> demonstrates that you are importing using character data format. CSV files and other text-based data sources are imported using it.</li>
<li><code class=" prettyprinted"><span class="pun">-</span><span class="pln">T </span><span class="str">','</span></code> is the field terminator used in the CSV file. In this case, it’s a comma (<code class=" prettyprinted"><span class="pun">,</span></code>), which is common for CSV files. This parameter tells BCP how to recognize the boundaries between fields in the CSV data.</li>
</ul>
<p>The BULK INSERT and BCP methods both handle bulk data operations, but they do so in different ways. Let&#8217;s examine their parallels and discrepancies.</p>
<p><strong>Similarities</strong>:</p>
<ul>
<li>Efficient transfer of large volumes of data into SQL Server tables.</li>
<li>Optimized for high-performance data loading.</li>
<li>Support for data import from external sources into SQL Server tables.</li>
</ul>
<p><strong>Differences</strong>:</p>
<ul>
<li>A command-line tool called BCP is used to import and export data into SQL Server.<br />
A Transact-SQL statement executed by SQL Server is called BULK INSERT. It is limited to data import.</li>
<li>Database administrators and developers who are comfortable using command-line tools can use BCP. As a result, additional setup and configurations might be needed.<br />
For SQL Server users and database developers who are accustomed to writing SQL queries, BULK INSERT is more convenient.</li>
<li>Security issues may arise if BCP asks for login information and passwords to be passed as command-line arguments.<br />
When using the SQL Server login, BULK INSERT can be more secure, especially when combined with security features built into the SQL Server database.</li>
</ul>
<h2 id="introduction-to-data-pump" class="wp-block-heading">Introduction to Data Pump</h2>
<p>DbForge Data Pump for SQL Server is your go-to option when you need to easily and quickly export/import data from external files to SQL Server databases. It is a powerful and adaptable SQL Server Management Studio data migration add-in for transferring data between different database systems and populating databases with data from external sources, regardless of their formats or structures. The tool supports the export and import of data in popular formats like Excel, CSV, XML, JSON, Text, MS Access, etc. Additionally, you can use a template file that has the same settings that apply to export/import operations to handle repetitive situations.</p>
<p>Let&#8217;s use dbForge Data Pump to import data from MS Access tables to brand-new SQL Server tables.</p>
<h2 id="retrieving-all-tables-from-an-ms-access-database" class="wp-block-heading">Retrieving all tables from an MS Access database</h2>
<p>Make the Microsoft Access file with the data that will be imported into SQL Server tables first. First, run the following SELECT statement to get a list of all tables from an MS Access database:</p>
<pre class="lang:default decode:true ">SELECT name FROM MSysObjects WHERE type = 4</pre>
<p>where:</p>
<ul>
<li><code class=" prettyprinted"><span class="pln">name</span></code> specifies the &#8220;name&#8221; column from the &#8220;MSysObjects&#8221; table that you want to retrieve. Query names as well as those of other database objects are typically stored in the &#8220;name&#8221; column.</li>
<li><code class=" prettyprinted"><span class="typ">MSysObjects</span></code> is a Microsoft Access system table that contains data on various database objects.</li>
<li><code class=" prettyprinted"><span class="pln">type </span><span class="pun">=</span><span class="pln"> </span><span class="lit">4</span></code> indicates a filtering condition for the results. A &#8220;type&#8221; with the value 4 typically refers to tables or saved queries in Microsoft Access. Consequently, the query instructs the database to only choose rows where the &#8220;MSysObjects&#8221; table&#8217;s &#8220;type&#8221; column equals 4.</li>
</ul>
<p>Once finished, save a file with the extension.accdb.</p>
<p>Proceed to using dbForge Data Pump to import data after that.</p>
<p>Let&#8217;s make sure the tables that will receive the data import are empty. Open SSMS and run the SELECT statements to retrieve the data to accomplish this.</p>
<p><img decoding="async" class="alignnone size-full wp-image-3748" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/empty-tables-data-pump.png" alt="" width="1000" height="534" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/empty-tables-data-pump.png 1000w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/empty-tables-data-pump-300x160.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/empty-tables-data-pump-768x410.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/empty-tables-data-pump-50x27.png 50w" sizes="(max-width: 1000px) 100vw, 1000px" /></p>
<p>As you can see, the tables are currently empty, so we can move on to filling them with data.</p>
<h2 id="create-a-template-to-import-settings" class="wp-block-heading">Create a template to import settings</h2>
<p>To make things simple, we&#8217;ll use the Data Import wizard in dbForge Data Pump to create a template with predefined import settings. By removing the need to manually configure import settings for each import operation, templates save time and effort. You can reuse a template with the desired settings rather than starting from scratch, which streamlines the import procedure and lowers the possibility of human error.</p>
<p>To facilitate data transfer between Microsoft Access files and non-Microsoft Office applications to other data sources like Microsoft SQL Server, download and install Microsoft Access Database Engine beforehand. If not, the Import wizard will display the following error:</p>
<p><img decoding="async" class="size-full wp-image-3749 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/error-with-drivers-data-pump.png" alt="" width="515" height="143" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/error-with-drivers-data-pump.png 515w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/error-with-drivers-data-pump-300x83.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/error-with-drivers-data-pump-50x14.png 50w" sizes="(max-width: 515px) 100vw, 515px" /></p>
<p>Once all the necessary steps have been taken, right-click the required database in SSMS Object Explorer and choose Data Pump &gt; Import Data to launch the Data Import Wizard.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3750" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/open-data-import-wizard.png" alt="" width="1000" height="542" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/open-data-import-wizard.png 1000w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/open-data-import-wizard-300x163.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/open-data-import-wizard-768x416.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/open-data-import-wizard-50x27.png 50w" sizes="(max-width: 1000px) 100vw, 1000px" /></p>
<p>Select an.mdb format in the wizard and the source file from which data will be imported before clicking Next.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-3751 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/choose-source-file-data-pump.png" alt="" width="781" height="753" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/choose-source-file-data-pump.png 781w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/choose-source-file-data-pump-300x289.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/choose-source-file-data-pump-768x740.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/choose-source-file-data-pump-50x48.png 50w" sizes="(max-width: 781px) 100vw, 781px" /></p>
<p>Choose a database, a table to import data to, a source table, and a target connection on the destination page. Next, select Next.</p>
<p>The Data Import wizard opens with the predefined connection parameters of the chosen table if it is launched from Object Explorer.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-3752 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/destination-page-data-pump.png" alt="" width="781" height="753" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/destination-page-data-pump.png 781w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/destination-page-data-pump-300x289.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/destination-page-data-pump-768x740.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/destination-page-data-pump-50x48.png 50w" sizes="(max-width: 781px) 100vw, 781px" /></p>
<p>You can, at your discretion, go through every page of the wizard to enter the necessary details and settings.</p>
<p>To create a template, click Save Template at the bottom of the wizard, enter the name and location of your template, and then click Save. It is advised to keep the template and all related files on your primary D: hard drive for proper operation.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-3753 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/save-template-data-pump-1024x752-1.png" alt="" width="1024" height="752" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/save-template-data-pump-1024x752-1.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/save-template-data-pump-1024x752-1-300x220.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/save-template-data-pump-1024x752-1-768x564.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/save-template-data-pump-1024x752-1-50x37.png 50w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>Done! The template is ready to use. Now, we can import data in bulk with the PowerShell script.</p>
<h2 id="automating-bulk-data-import" class="wp-block-heading">Automating bulk data import</h2>
<p>The PowerShell script is made up of a series of commands that PowerShell is told to run in order to carry out various tasks.</p>
<p>Let&#8217;s write a PowerShell script that details every action it takes to import data in bulk.</p>
<p>1. Open the Windows Integrated Scripting Environment (ISE) console for PowerShell.</p>
<p>2. Click New Script on the toolbar and type the following guidelines:</p>
<pre class="lang:default decode:true "># Define the path to the Microsoft Access database
$dbPath = "D:\og.accdb"

# Path to your DBForge
$diffToolLocation = "C:\Program Files\Devart\dbForge SQL Tools Professional\dbForge Data Pump for SQL Server\datapump.com"

# Define the provider and the data source
$connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$dbPath`";"

# Create a new OleDb connection
$connection = New-Object System.Data.OleDb.OleDbConnection($connectionString)

# Open the connection
$connection.Open()

# Get the schema information for the data source
$tables = $connection.GetSchema('Tables')

# Filter out system tables to get only user tables
$userTables = $tables | Where-Object { $_.TABLE_TYPE -eq 'TABLE' -and $_.TABLE_NAME -notlike 'MSys*' }

# Process each table
$userTables | ForEach-Object {
    $tableName = $_.TABLE_NAME
    Write-Output "Processing table: $tableName"
    
    #Command-line string for importing data into your SQL Server database
    $process = Start-Process -FilePath $diffToolLocation -ArgumentList "/dataimport /templatefile:`"D:\imptemplate.dit`" /connection:`"Data Source=&lt;server_name&gt;;Integrated Security=True;User ID=&lt;username&gt;`" /inputfile:`"D:\og.accdb`" /inputtable:$tableName /table:`"Olympic_Games_Dev.dbo.$tableName`" /errormode:abort" #-PassThru -Wait -windowstyle hidden         
    
    #If you need to process the tables one by one to reduce server load - uncomment it.
    #Start-Sleep -Seconds 10                        
                            }

# Close the connection
$connection.Close()</pre>
<p>3. Substitute the following arguments with your relevant data:</p>
<ul>
<li><code class=" prettyprinted"><span class="pln">$dbPath</span></code>: The source MS Access file&#8217;s path, from which data should be imported.</li>
<li><code class=" prettyprinted"><span class="pln">$diffToolLocation</span></code>: The location of the dbForge Data Pump installation folder.</li>
<li><code class=" prettyprinted"><span class="pln">$connectionString</span></code>: Microsoft Access databases in the.accdb file format can be interacted with using the OLE DB Provider.</li>
<li><code class=" prettyprinted"><span class="pun">/</span><span class="pln">templatefile</span></code>: How to get to the template.you used the Data Import wizard to create the dit file.</li>
<li><code class=" prettyprinted"><span class="pun">/</span><span class="pln">connection</span></code>: Connection specifications for the target database tables that you want to import data into.</li>
<li><code class=" prettyprinted"><span class="pun">/</span><span class="pln">inputfile</span></code>: Name of the source file that should be used to import data.</li>
<li><code class=" prettyprinted"><span class="pun">/</span><span class="pln">table</span></code>: Full name of the target SQL Server table, including the database and associated schema, for instance, <em>Olympic_Games_Dev.dbo.$tableName</em>.</li>
</ul>
<p>Due to the fact that we declared the variable $tableName, all tables present in the database will be processed without your having to manually enter their names. This will streamline the procedure and lower the likelihood of errors.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-3754 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/run-powershell-data-pump.png" alt="" width="1000" height="601" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/run-powershell-data-pump.png 1000w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/run-powershell-data-pump-300x180.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/run-powershell-data-pump-768x462.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/run-powershell-data-pump-50x30.png 50w" sizes="(max-width: 1000px) 100vw, 1000px" /></p>
<p>After the script has been written, you can run it by selecting Run Script from the toolbar.</p>
<p>Done! Return to dbForge Data Pump at this time to confirm that the data has been moved from MS Access to the SQL Server database tables. Execute the SELECT statements to achieve this.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3755" src="https://topreviewhostingasp.net/wp-content/uploads/2023/10/result-data-pump.png" alt="" width="1004" height="840" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/10/result-data-pump.png 1004w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/result-data-pump-300x251.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/result-data-pump-768x643.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/10/result-data-pump-50x42.png 50w" sizes="(max-width: 1004px) 100vw, 1004px" /></p>
<p>The result shows the tables that have been filled with information.</p>
<h2 class="wp-block-heading">Conclusion</h2>
<p>In conclusion, bulk data import is a crucial task in database administrators&#8217; day-to-day responsibilities. In this article, we reviewed the procedures for transferring data between databases, specifically how to import Microsoft Access data into SQL Server. Additionally, we have shown how to use the PowerShell ISE script and dbForge Data Pump to import data in bulk. Making a template, updating the script&#8217;s arguments with your actual data, and running the script are all that are required.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-automate-bulk-data-import-from-ms-access-to-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Reduce Connection Pools Hitting Multiple Databases</title>
		<link>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/</link>
					<comments>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 16 Feb 2023 07:09:12 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[database issue]]></category>
		<category><![CDATA[fix connection pool issue]]></category>
		<category><![CDATA[sql database]]></category>
		<category><![CDATA[sql database hang]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tips]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3434</guid>

					<description><![CDATA[Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a single database and all your connections use the same connection string. It even works well if you have two or three different connection strings, but for each unique connection string value, the .Net Framework creates a new connection pool. If your web site has dozens of different databases to connect to, you may find your application creates dozens of connection pools which begins to consume a lot of resources on both the web server and SQL Server.</p>



<p>There is a fairly easy way to eliminate this problem, and that is to use the ChangeDatabase method on the Connection object.</p>



<p>Our web application was connecting to one of fifty different databases that all reside on the same instance of SQL Server. Each of our clients has their own database. But our application was creating fifty different connection pools. We were able to have all the clients share a single pool of connections by first connecting to a neutral database, then redirecting the connection to the desired database.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.asphostportal.com" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure></div>


<p>We created a new database on the server, called Central, then we had all the connections to the database first connect to Central as the Initial Catalog. The next step was to call ChangeDatabase to switch to the desired database. This technique did not create a new connection to SQL Server and did not create a new connection pool on the .Net client. Microsoft documentation mentions this technique here: <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases</a> , but their example code does not show the ChangeDatabase method, which is more efficient than their example.</p>



<p>In a nutshell, you can do this:</p>



<pre class="wp-block-code"><code>connection.Open();
connection.ChangeDatabase(“Client1”);</code></pre>



<p>I created a simple Windows Form App to test the idea.  The test app runs a query to return the name of the current database it is in.  Also, on the SQL Server I run a query to see all the connections that exist.  Doing this I was able to prove that using ChangeDatabase did not create a new connection to SQL Server and my .Net SQL Connection Object was pointing at the correct desired database.  Sample code, query, and output is below:</p>



<p>Sample C# .Net Forms App:</p>



<pre class="wp-block-code"><code>using System;
using System.Data.SqlClient;
using System.Windows.Forms;
 
namespace SQLConnectionTest
{
    public partial class Form1 : Form
    {
        //https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases
        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=model;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=msdb;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            { 
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
            }
 
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
                connection.ChangeDatabase("model");
                RunSQL(connection, "select DB_NAME()");
            }
        }
 
        public static void RunSQL(SqlConnection connection, string queryString)
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                SqlDataReader reader = command.ExecuteReader(); 
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("\t{0}", reader[0]);
                    }
                    reader.Close();
                }
            }
            catch (Exception ex){Console.WriteLine(ex.Message);}
        }
        public Form1()
        {
            InitializeComponent();
        }
 
 
    }
}</code></pre>



<p>Output from Running the App written to console:</p>



<pre class="wp-block-code"><code>master
model
msdb
master
tempdb
master
tempdb
model</code></pre>



<p>Query to see connections on SQL Server:</p>



<pre class="wp-block-code"><code>CREATE TABLE #TmpLog
(SPID int, Status VARCHAR(150), Login varchar(100), HostName VARCHAR(150), BlkBy varchar(30), DBName varchar(60), Command varchar(500),
CPUTime int, DiskIO int, LastBatch varchar(20), ProgramName varchar(200), SPID2 int, requestid int)
INSERT INTO #TmpLog
EXEC sp_who2
SELECT SPID, Status, Login, HostName, BlkBy, DBName, Command, ProgramName
FROM #TmpLog
where STATUS not in (‘BACKGROUND’) and Command not in (‘TASK MANAGER’) and ProgramName like ‘.net%’
DROP TABLE #TmpLog
go</code></pre>



<p>Results of running query on SQL Server:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="143" class="wp-image-3435" src="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-300x42.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-768x107.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1536x214.png 1536w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-50x7.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query.png 2013w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use Entity Framework Connect to SQL Server</title>
		<link>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 18 Mar 2022 07:44:06 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[.net core 6]]></category>
		<category><![CDATA[asp net core 6 tips]]></category>
		<category><![CDATA[asp net core 6 tutorial]]></category>
		<category><![CDATA[entity framework tips]]></category>
		<category><![CDATA[entity framework tutorial]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3013</guid>

					<description><![CDATA[This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations. We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This post shows goes through the steps to connect a .NET 6 API to SQL Server using Entity Framework Core, and automatically create/update the SQL Server database from code using EF Core migrations.</p>



<p>We&#8217;ll start with an example .NET 6 CRUD API from a tutorial I posted recently, it uses the EF Core InMemory db provider by default for testing, we&#8217;ll update it to connect to a SQL Server database and run EF Core migrations to auto generate the database and tables from code. </p>



<h2 class="wp-block-heading">Requirements!</h2>



<p>To follow the steps in this tutorial you&#8217;ll need the following:</p>



<ul>
<li><a href="https://dotnet.microsoft.com/download" target="_blank" rel="noreferrer noopener">.NET SDK</a> &#8211; includes the .NET runtime and command line tools.</li>
<li><a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a> &#8211; code editor that runs on Windows, Mac and Linux. If you have a different preferred code editor that&#8217;s fine too.</li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp" target="_blank" rel="noreferrer noopener">C# extension</a> for Visual Studio Code &#8211; adds support to VS Code for developing .NET applications.</li>
<li>SQL Server &#8211; you&#8217;ll need access to running SQL Server instance for the API to connect to, it can be remote (e.g. Azure, AWS etc) or on your local machine. The Express edition of SQL Server is available for free at <a href="https://www.microsoft.com/sql-server/sql-server-downloads" target="_blank" rel="noreferrer noopener">https://www.microsoft.com/sql-server/sql-server-downloads</a>.</li>
</ul>



<h2 class="wp-block-heading">Download &amp; Run the example .NET 6 API</h2>



<p>Follow these steps to download and run the .NET 6 CRUD API on your local machine with the default EF Core InMemory database:</p>



<ol>
<li>Download or clone the tutorial project code from <a href="https://github.com/cornflourblue/dotnet-6-crud-api" target="_blank" rel="noreferrer noopener">https://github.com/cornflourblue/dotnet-6-crud-api</a></li>
<li>Start the api by running <code>dotnet run</code> from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message <code>Now listening on: http://localhost:4000</code>.</li>
<li>You can test the API directly with a tool such as <a href="https://www.postman.com/downloads" target="_blank" rel="noreferrer noopener">Postman</a>.</li>
</ol>



<h4 class="wp-block-heading">Starting in debug mode</h4>



<p>You can also start the application in debug mode in VS Code by opening the project root folder in VS Code and pressing F5 or by selecting Debug -&gt; Start Debugging from the top menu, running in debug mode allows you to attach breakpoints to pause execution and step through the application code.</p>



<h2 class="wp-block-heading">Update .NET 6 API to use SQL Server</h2>



<h4 class="wp-block-heading"><br />Add SQL Server database provider from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core database provider for SQL Server from NuGet:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.SqlServer</code></pre>



<h4 class="wp-block-heading">Add connection string to app settings</h4>



<p>Open the <code>appsettings.json</code> file and add the entry <code>"ConnectionStrings"</code> with a child entry for the SQL Server connection string (e.g. <code>"WebApiDatabase"</code>), the connection string should be in the format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; User Id=[USERNAME]; Password=[PASSWORD]"</code>, or to connect with the same account that is running the .NET API use the connection string format <code>"Data Source=[DB SERVER URL]; Initial Catalog=[DB NAME]; Integrated Security=true"</code>.</p>



<p>When EF Core migrations generates the database, the <code>Initial Catalog</code> value will be the name of the database created in SQL Server.</p>



<p>The updated <code>appsettings.json</code> file with the connection string should look something like this:</p>



<pre class="wp-block-code"><code>{
    "ConnectionStrings": {
        "WebApiDatabase": "Data Source=localhost; Initial Catalog=dotnet-6-crud-api; User Id=testUser; Password=testPass123"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    }
}</code></pre>



<h4 class="wp-block-heading">Update Data Context to Use SQL Server</h4>



<p>The <code>DataContext</code> class located at <code>/Helpers/DataContext.cs</code> is used for accessing application data through Entity Framework. It derives from the Entity Framework <code>DbContext</code> class and has a public <code>Users</code> property for accessing and managing user data.</p>



<p>Update the <code>OnConfiguring()</code> method to connect to SQL Server instead of an in memory database by replacing <code>options.UseInMemoryDatabase("TestDb");</code> with <code>options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));</code>.</p>



<p>The updated <code>DataContext</code> class should look like this:</p>



<pre class="wp-block-code"><code>namespace WebApi.Helpers;

using Microsoft.EntityFrameworkCore;
using WebApi.Entities;

public class DataContext : DbContext
{
    protected readonly IConfiguration Configuration;

    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // connect to sql server with connection string from app settings
        options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));
    }

    public DbSet&lt;User&gt; Users { get; set; }
}</code></pre>



<h2 class="wp-block-heading">Create SQL Database from code with EF Core Migrations</h2>



<h4 class="wp-block-heading"><br />Install dotnet ef tools</h4>



<p>The .NET Entity Framework Core tools (<code>dotnet ef</code>) are used to generate EF Core migrations, to install the EF Core tools globally run <code>dotnet tool install -g dotnet-ef</code>, or to update run <code>dotnet tool update -g dotnet-ef</code>. For more info on EF Core tools see <a href="https://docs.microsoft.com/ef/core/cli/dotnet" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/ef/core/cli/dotnet</a></p>



<h4 class="wp-block-heading">Add EF Core Design package from NuGet</h4>



<p>Run the following command from the project root folder to install the EF Core design package, it provides cross-platform command line tooling support and is used to generate EF Core migrations:</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore.Design</code></pre>



<h4 class="wp-block-heading">Generate EF Core migrations</h4>



<p>Generate new EF Core migration files by running the command <code>dotnet ef migrations add InitialCreate</code> from the project root folder (where the WebApi.csproj file is located), these migrations will create the database and tables for the .NET Core API.</p>



<h4 class="wp-block-heading">Execute EF Core migrations</h4>



<p>Run the command <code>dotnet ef database update</code> from the project root folder to execute the EF Core migrations and create the database and tables in SQL Server.</p>



<p>Check SQL Server and you should now see your database with the tables <code>Users</code> and <code>__EFMigrationsHistory</code>.</p>



<h2 class="wp-block-heading">Restart .NET 6.0 CRUD API</h2>



<p>Stop and restart the API with the command <code>dotnet run</code> from the project root folder, you should see the message <code>Now listening on: http://localhost:4000</code> and the API should now be connected to SQL Server.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-entity-framework-connect-to-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create Entity Core Migrations for SQLite and SQL Server</title>
		<link>https://topreviewhostingasp.net/how-to-create-entity-core-migrations-for-sqlite-and-sql-server/</link>
					<comments>https://topreviewhostingasp.net/how-to-create-entity-core-migrations-for-sqlite-and-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 28 May 2021 07:55:45 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[entity framework database migration]]></category>
		<category><![CDATA[entity framework migration]]></category>
		<category><![CDATA[entity framework tips]]></category>
		<category><![CDATA[entity framework tutorial]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sqlite]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2965</guid>

					<description><![CDATA[In this post we&#8217;ll go through an example of how to setup an ASP.NET Core project with EF Core DB Contexts and Migrations that support multiple different database providers. The below steps show how to use a SQLite database in development and a SQL Server database in production, but you could switch these to any [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this post we&#8217;ll go through an example of how to setup an ASP.NET Core project with EF Core DB Contexts and Migrations that support multiple different database providers.</p>



<p>The below steps show how to use a SQLite database in development and a SQL Server database in production, but you could switch these to any database providers you like that are supported by EF Core.</p>



<h2 class="wp-block-heading">Create Main EF Core DB Context for SQL Server</h2>



<p>Create the main DB context class that defines the entities available in the database via <code>public DbSet&lt;TEntity&gt;</code> properties, and configure it to connect to the production database (SQL Server in this case).</p>



<p>Below is the main DB context from the example ASP.NET Core api linked above, it has the class name <code>DataContext</code> and is located in the <code>/Helpers</code> directory of the project, but you can choose any class name and directory you prefer.</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using WebApi.Entities;

namespace WebApi.Helpers
{
    public class DataContext : DbContext
    {
        protected readonly IConfiguration Configuration;

        public DataContext(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // connect to sql server database
            options.UseSqlServer(Configuration.GetConnectionString("WebApiDatabase"));
        }

        public DbSet&lt;User&gt; Users { get; set; }
    }
}</code></pre>



<h2 class="wp-block-heading">Create Development EF Core DB Context for SQLite</h2>



<p>Create a development DB context that inherits from the main DB context above and overrides the database provider in the <code>OnConfiguring()</code> method.</p>



<p>Below is the development DB context from the example ASP.NET Core api that overrides the database provider to connect to SQLite instead of SQL Server. Having a second EF Core DB Context that derives from the main DB context is what enables the project to support multiple different database providers.</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace WebApi.Helpers
{
    public class SqliteDataContext : DataContext
    {
        public SqliteDataContext(IConfiguration configuration) : base(configuration) { }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // connect to sqlite database
            options.UseSqlite(Configuration.GetConnectionString("WebApiDatabase"));
        }
    }
}</code></pre>



<h2 class="wp-block-heading">Generate SQLite EF Core Migrations</h2>



<p>Run the following command to generate EF Core migrations for SQLite and store them in their own folder.</p>



<pre class="wp-block-code"><code>dotnet ef migrations add InitialCreate --context SqliteDataContext --output-dir Migrations/SqliteMigrations
</code></pre>



<h2 class="wp-block-heading">Generate SQL Server EF Core Migrations</h2>



<p>Run the following command to generate EF Core migrations for SQL Server and store them in their own folder.</p>



<p>The environment variable <code>ASPNETCORE_ENVIRONMENT</code> needs to be set to <code>Production</code> so the SQL Server <code>DataContext</code> class is configured with the .NET Core dependency injection system, see the <code>ConfigureServices()</code> method below.</p>



<p>Configuring environment variables from the command line is slightly different on MacOS and Windows.</p>



<p><strong>Windows</strong></p>



<pre class="wp-block-code"><code>set ASPNETCORE_ENVIRONMENT=Production
dotnet ef migrations add InitialCreate --context DataContext --output-dir Migrations/SqlServerMigrations</code></pre>



<p><strong>MacOS</strong></p>



<pre class="wp-block-code"><code>ASPNETCORE_ENVIRONMENT=Production dotnet ef migrations add InitialCreate --context DataContext --output-dir Migrations/SqlServerMigrations
</code></pre>



<h2 class="wp-block-heading">Configure Startup.cs to use SQLite in Development and SQL Server in Production</h2>



<p>Below is a cut down version of the Startup.cs file from the example ASP.NET Core api that just includes the bits related to the EF Core DB context configuration and automatic database migration.</p>



<p>Lines <code>23 - 26</code> configure which type of data context is injected by the .NET Core dependency injection system when a <code>DataContext</code> instance is required by a class. In production an instance of the main <code>DataContext</code> class is used which connects to SQL Server, otherwise (i.e. in development) an instance of the <code>SqliteDataContext</code> is used.</p>



<p>An instance of the <code>DataContext</code> is injected as a parameter into the <code>Configure()</code> method, the data context instance is then used to apply any pending migrations to the database by calling the <code>dataContext.Database.Migrate()</code> method on line <code>35</code>.</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using WebApi.Helpers;

namespace WebApi
{
    public class Startup
    {
        private readonly IWebHostEnvironment _env;

        public Startup(IWebHostEnvironment env)
        {
            _env = env;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // use sql server db in production and sqlite db in development
            if (_env.IsProduction())
                services.AddDbContext&lt;DataContext&gt;();
            else
                services.AddDbContext&lt;DataContext, SqliteDataContext&gt;();

            ...
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
        {
            // migrate any database changes on startup (includes initial db creation)
            dataContext.Database.Migrate();
            
            ...
        }
    }
}</code></pre>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-create-entity-core-migrations-for-sqlite-and-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Use Serilog ASP.NET Core to SQL Server Database</title>
		<link>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/</link>
					<comments>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 03 Dec 2020 04:03:24 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp.net core hosting]]></category>
		<category><![CDATA[asp.net core tips]]></category>
		<category><![CDATA[asp.net core tutorial]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[serilog asp net core]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[web host asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2813</guid>

					<description><![CDATA[Logging is an essential feature for any application, as it is necessary for detecting, investigating, and debugging issues. Serilog is a third-party, open source library that allows .NET developers to log structured data to the console, to files, and to several other kinds of data stores.  This article discusses how we can use Serilog to log structured [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Logging is an essential feature for any application, as it is necessary for detecting, investigating, and debugging issues. <a href="https://serilog.net/">Serilog</a> is a third-party, open source library that allows .NET developers to log structured data to the console, to files, and to several other kinds of data stores. </p>



<p>This article discusses how we can use Serilog to log structured data to a SQL Server database. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system.</p>



<h2 class="wp-block-heading">Create Your First ASP.NET Core 3.0 Project</h2>



<p>Make sure you create your ASP.NET Core project in Visual Studio. We assume that you have installed Visual Studio on your computer.</p>



<h2 class="wp-block-heading">Install the NuGet packages for Serilog</h2>



<p>To work with Serilog, you should install the Serilog packages from NuGet. You can do this either via the NuGet package manager inside the Visual Studio 2019 IDE, or by executing the following commands at the NuGet package manager console:</p>



<pre class="wp-block-code"><code>Install-Package Serilog
Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.MSSqlServer
Install-Package Serilog.Settings.Configuration</code></pre>



<h2 class="wp-block-heading">Initialize Serilog in Program.cs in ASP.NET Core</h2>



<p>The following code snippet illustrates how you can plug Serilog into ASP.NET Core. Note how the UseSerilog() extension method has been used to set Serilog as the logging provider.</p>



<pre class="wp-block-code"><code>public static IWebHost BuildWebHost(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                   .UseStartup&lt;Startup&gt;()
                   .UseSerilog()
                   .Build();</code></pre>



<h2 class="wp-block-heading">Build an example web host in ASP.NET Core</h2>



<p>Naturally, we’ll need an application to illustrate the use of Serilog. Here is the complete source code of the Program class for our example app. Note how we’ve configured and built the web host.</p>



<pre class="wp-block-code"><code>    public class Program
    {
        public static void Main(string[] args)
        {
            IConfigurationRoot configuration = new
            ConfigurationBuilder().AddJsonFile("appsettings.json",
            optional: false, reloadOnChange: true).Build();
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration
            (configuration).CreateLogger();
            BuildWebHost(args).Run();
        }
        public static IWebHost BuildWebHost(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                .UseStartup&lt;Startup&gt;()
                .UseSerilog()
                .Build();
    }</code></pre>



<h2 class="wp-block-heading">Configure database connection settings in ASP.NET Core</h2>



<p>When you create a new ASP.NET Core project in Visual Studio, the appsettings.json file is created by default. Here is where you can specify the database connection string and other configuration information. Open the appsettings.json file from the project we created earlier and enter the following information:</p>



<pre class="wp-block-code"><code>{
  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Data Source=LAPTOP-ULJMOJQ5;Initial
           Catalog=Research;    
     User Id=joydip; Password=sa123#;",
          "tableName": "Log",
          "autoCreateSqlTable": true
        }
      }
    ]
  }
}</code></pre>



<h2 class="wp-block-heading">Create a database table to log data in SQL Server</h2>



<p>You might want to create the log table yourself as well. Below is the script you can use to create a log table in the SQL Server database.</p>



<pre class="wp-block-code"><code>CREATE TABLE [Log] (
   [Id] int IDENTITY(1,1) NOT NULL,
   [Message] nvarchar(max) NULL,
   [MessageTemplate] nvarchar(max) NULL,
   [Level] nvarchar(max) NULL,
   [TimeStamp] datetimeoffset(7) NOT NULL,
   [Exception] nvarchar(max) NULL,
   [Properties] nvarchar(max) NULL
   CONSTRAINT [PK_Log]
     PRIMARY KEY CLUSTERED ([Id] ASC)
)</code></pre>



<p>When you run the application, a new table named Log will be created and the ASP.NET Core startup events will be logged there. Figure 1 below shows the data that has been logged inside the Log table.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="447" class="wp-image-2816" src="https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-1024x447.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-1024x447.jpg 1024w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-300x131.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-768x335.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-50x22.jpg 50w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Log data in action methods in ASP.NET Core</h2>



<p>You can leverage dependency injection to inject a logger instance in your controller as shown in the code snippet below:</p>



<pre class="wp-block-code"><code>public class DefaultController : Controller
{
   private readonly ILogger&lt;DefaultController&gt; _logger;
   public DefaultController(ILogger&lt;DefaultController&gt; logger)
   {
      _logger = logger;
   }
}</code></pre>



<p>The following code snippet illustrates how you can take advantage of Serilog in your controller’s action methods to log data.</p>



<pre class="wp-block-code"><code>public class DefaultController : Controller
    {
        private readonly ILogger&lt;DefaultController&gt; _logger;
        public DefaultController(ILogger&lt;DefaultController&gt; logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            _logger.LogInformation("Hello World");
            return View();
        }
    }</code></pre>



<p>Although independent of .NET Core, Serilog plugs into the ASP.NET Core ecosystem nicely, making structured logging easy and convenient. Serilog also takes advantage of <a href="https://github.com/serilog/serilog/wiki/Provided-Sinks">dozens of sinks</a> to send the logs to many different logging targets ranging from text files to databases to hosting providers. I will post other interesting post in next post.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
