<?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>.net core 6 &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/net-core-6/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Fri, 18 Mar 2022 07:48:28 +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>.net core 6 &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>
	</channel>
</rss>
