<?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>entity framework migration &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/entity-framework-migration/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, 28 May 2021 07:58:50 +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>entity framework migration &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>How to Use Entity Framework 5 in .NET Core 3 to Implement Code-First Approach</title>
		<link>https://topreviewhostingasp.net/how-to-use-entity-framework-5-in-net-core-3-to-implement-code-first-approach/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-entity-framework-5-in-net-core-3-to-implement-code-first-approach/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 04 Feb 2021 03:35:33 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[.net core 3]]></category>
		<category><![CDATA[.net core 3 tips]]></category>
		<category><![CDATA[.net core 3 tutorial]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[entity framework 5]]></category>
		<category><![CDATA[entity framework migration]]></category>
		<category><![CDATA[entity framework tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2879</guid>

					<description><![CDATA[In this article, I will show tutorial about how to use EF Core 5.0 in .NET Core 3.1 to implement Code-First approach to create/update MySQL database on Visual Studio 2019 for a RESTful API application. Let’s get started.  Step 1 &#8211; Create .NET Core 3.1 project on Visual Studio 2019  We will create a RESTful [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, I will show tutorial about how to use EF Core 5.0 in .NET Core 3.1 to implement Code-First approach to create/update MySQL database on Visual Studio 2019 for a RESTful API application.</p>



<p>Let’s get started. </p>



<p><strong>Step 1 &#8211; Create .NET Core 3.1 project on Visual Studio 2019</strong> </p>



<p>We will create a RESTful API project with .NET Core 3.1 on Visual Studio 2019 (FYI: we use Microsoft Visual Studio Professional 2019 Version 16.8.0). VS 2019 &#8211; File &#8211; New &#8211; Project… choose “ASP.NET Core Web Application” &#8211; Next,</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="652" height="446" class="wp-image-2880 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/new-project-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/new-project-1.png 652w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/new-project-1-300x205.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/new-project-1-50x34.png 50w" sizes="(max-width: 652px) 100vw, 652px" /></figure>



<p>Enter project name “EFCoreMySQL” (whatever you like), select the location you want, click “Create” button,</p>



<figure class="wp-block-image size-large"><img decoding="async" width="652" height="447" class="wp-image-2881 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-2.png 652w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-2-300x206.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-2-50x34.png 50w" sizes="(max-width: 652px) 100vw, 652px" /></figure>



<p>Make sure “ASP.NET Core 3.1” is selected, and also “API” is chosen as the project template. “Configure for HTTPS” and “Enable Docker Support” can be checked or unchecked based on your needs. Click the “Create” button.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="720" height="499" class="wp-image-2882 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-3.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-3-300x208.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-3-50x35.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Wait a while, the project “EFCoreMySQL” is created successfully:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="354" class="wp-image-2883 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-4.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-4.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-4-300x148.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-4-50x25.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>On VS 2019 ribbon, click the drop-down as shown below, select “Google Chrome”, then select “IIS Express”. The dropdown will close and show “IIS Express”. Click “IIS Express” to build &amp; run for a test.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="354" class="wp-image-2884 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-5.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-5.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-5-300x148.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-5-50x25.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>The default weather data is shown on the page:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="357" class="wp-image-2885 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-6.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-6.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-6-300x149.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-6-50x25.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p><strong><br />Step 2 &#8211; Install dependency packages</strong> </p>



<p>In order to use Entity Framework Core to implement the Code-First approach to MySQL database, we need to install following packages of dependencies to the project:</p>



<ul>
<li>Microsoft.EntityFrameworkCore (v5.0.0 – the latest stable version)</li>
<li>Microsoft.EntityFrameworkCore.Tools (v5.0.0 – the latest stable version)</li>
<li>Pomelo.EntityFrameworkCore.MySql (version 5.0.0-alpha.2)</li>
</ul>



<p>Pomelo.EntityFrameworkCore.MySql is the most popular Entity Framework Core provider for MySQL compatible databases. It supports EF Core 3.1 (and lower) and uses MySqlConnector for high-performance database server communication. </p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com"><img loading="lazy" decoding="async" width="250" height="250" class="wp-image-2903 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01.png 250w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01-150x150.png 150w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01-50x50.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01-70x70.png 70w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01-127x127.png 127w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/banner-affiliate-ahp-01-125x125.png 125w" sizes="(max-width: 250px) 100vw, 250px" /></a></figure>
</div>



<p>The following versions of MySqlConnector, EF Core, .NET Standard and .NET Core are compatible with Pomelo.EntityFrameworkCore.MySql. We can see that “5.0.0-alpha.2” is a pre-release version of Pomelo.EntityFrameworkCore.MySql, and so far it’s the only version that can work with EF Core 5.0.0 and .NET Core 3.1, that’s why we need to install “Pomelo.EntityFrameworkCore.MySql” of version “5.0.0-alpha.2” for the project.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="663" height="154" class="wp-image-2886 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-7.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-7.png 663w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-7-300x70.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-7-50x12.png 50w" sizes="(max-width: 663px) 100vw, 663px" /></figure>



<p>MySql.Data.EntityFrameworkCore latest version is 8.0.22 that is not working with EF Core 5. </p>



<p>Install “Microsoft.EntityFrameworkCore” (v5.0.0 – the latest stable version) VS 2019</p>



<p>&#8211; right-click the project node “EFCoreMySQL” in Solution Explorer <br />&#8211; Manage NuGet Packages… Browse <br />&#8211; enter “Microsoft.EntityFrameworkCore” to search <br />&#8211; select it and click the “Install” button to install.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="333" class="wp-image-2887 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-8.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-8.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-8-300x139.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-8-50x23.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>“Licence Acceptance” will pop up, click “I Accept” to continue:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="333" class="wp-image-2888 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-9.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-9.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-9-300x139.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-9-50x23.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Install “Microsoft.EntityFrameworkCore.Tools” (v5.0.0 – the latest stable version) VS 2019</p>



<p>&#8211; right-click the project node “EFCoreMySQL” in Solution Explorer <br />&#8211; Manage NuGet Packages… Browse <br />&#8211; enter “Microsoft.EntityFrameworkCore.Tools” to search <br />&#8211; select it and click “Install” button to install.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="333" class="wp-image-2889 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-10.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-10.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-10-300x139.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-10-50x23.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>“Licence Acceptance” will pop up, click “I Accept” to continue:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="333" class="wp-image-2890 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-11.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-11.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-11-300x139.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-11-50x23.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Install “Pomelo.EntityFrameworkCore.MySql” (version 5.0.0-alpha.2) For this pre-release version, we need to install it from the Package Manager Console. </p>



<p>&#8211; VS 2019 <br />&#8211; Tools <br />&#8211; NuGet Package Manager <br />&#8211; Package Manager Console <br />&#8211; enter “Install-Package Pomelo.EntityFrameworkCore.MySql -Version 5.0.0-alpha.2”, hit ENTER key to install:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="275" class="wp-image-2891 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-12.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-12.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-12-300x115.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-12-50x19.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Now we have all dependency packages installed on the project successfully:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="347" class="wp-image-2892 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-13.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-13.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-13-300x145.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/ef-13-50x24.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p><strong>Step 3 &#8211; Install MySQL Workbench and MySQL Server</strong> </p>



<p>In order to manage MySQL database, we need MySQL server that hosts MySQL database and also the management tool – MySQL Workbench. </p>



<p>We will briefly show how to install them on your machine. If you already have MySQL server and MySQL Workbench to use, then skip this step. </p>



<p>MySQL Community Server (latest version 8.0.22) is free to download and use. Go to Oracle MySQL Community Downloads page <em>https://dev.mysql.com/downloads/mysql/</em> to download the MSI package that suits your operating system, and then install both MySQL Workbench and MySQL Server from it on your machine. </p>



<p>You need to sign in to download the MSI package. In other words, you need to have an account there first for you to sign in. If you do not have an account yet, just create one. It’s free.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="696" height="768" class="wp-image-2893 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-1.png 696w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-1-272x300.png 272w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-1-45x50.png 45w" sizes="(max-width: 696px) 100vw, 696px" /></figure>



<p>Two things to remind, the first one is that on the MySQL Installer, you need to click “Add …” to select products to install, you can select “MySQL Server 8.0” and “MySQL Workbench 8.0”.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="541" class="wp-image-2894 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-2.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-2-300x225.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-2-50x38.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>The second thing is that along with the installation you will be asked to enter password for the root, you need to remember password for future use. </p>



<p>Once installation is done, you can double-check to make sure that MySQL Server is running on your machine. Simply run “MySQL 8.0 Command Line Client” (installed by the MySQL Server installation), and type “Show Databases;”</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="427" class="wp-image-2895 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-3.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-3-300x178.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-3-50x30.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>In MySQL Workbench, connect the MySQL Server. Run MySQL Workbench à click the “MySQL Connections” plus button to open “Setup New Connection” window &#8211; enter the connection name you like &#8211; click “Test Connection” button &#8211; enter the root password &#8211; check “Save password in vault” &#8211; click “OK” &#8211; click “OK” &#8211; click “OK”</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="440" class="wp-image-2896 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-4.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-4.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-4-300x183.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-4-50x31.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="440" class="wp-image-2897 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-5.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-5.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-5-300x183.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/MySQL-5-50x31.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p><strong>Step 4 &#8211; Create model classes</strong> </p>



<p>In VS 2019 Solution Explorer, create a folder at project root called “Models” (whatever you like), and add model classes in the folder. To simplify, we just add two classes “UserGroup” and “User”, </p>



<p><strong>UserGroup.cs</strong></p>



<pre class="wp-block-code"><code>using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace EFCoreMySQL.Models  
{  
    public class UserGroup  
    {  
        public int Id { get; set;}  
        public string Name { get; set;}  
        public DateTime CreationDateTime { get; set;}  
        public DateTime? LastUpdateDateTime { get; set;}  
    }  
} </code></pre>



<p><strong>User.cs</strong></p>



<pre class="wp-block-code"><code>using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace EFCoreMySQL.Models  
{  
    public class User  
    {  
        public int Id { get; set;}  
        public string FirstName { get; set;}  
        public string LastName { get; set;}  
        public int UserGroupId { get; set;}  
        public DateTime CreationDateTime { get; set;}  
        public DateTime? LastUpdateDateTime { get; set;}  
    }  
}  </code></pre>



<p><strong>Step 5 &#8211; Create a database context</strong> </p>



<p>In VS 2019 Solution Explorer, create a folder at project root called “DBContexts” (whatever you like), and add a class called “MyDBContext” with the following content:</p>



<pre class="wp-block-code"><code>using EFCoreMySQL.Models;  
using Microsoft.EntityFrameworkCore;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace EFCoreMySQL.DBContexts  
{  
    public class MyDBContext : DbContext  
    {  
        public DbSet&lt;UserGroup&gt; UserGroups { get; set; }  
        public DbSet&lt;User&gt; Users { get; set; }  
  
        public MyDBContext(DbContextOptions&lt;MyDBContext&gt; options) : base(options)  
        {   
        }  
  
        protected override void OnModelCreating(ModelBuilder modelBuilder)  
        {  
            // Use Fluent API to configure  
  
            // Map entities to tables  
            modelBuilder.Entity&lt;UserGroup&gt;().ToTable("UserGroups");  
            modelBuilder.Entity&lt;User&gt;().ToTable("Users");  
  
            // Configure Primary Keys  
            modelBuilder.Entity&lt;UserGroup&gt;().HasKey(ug =&gt; ug.Id).HasName("PK_UserGroups");  
            modelBuilder.Entity&lt;User&gt;().HasKey(u =&gt; u.Id).HasName("PK_Users");  
  
            // Configure indexes  
            modelBuilder.Entity&lt;UserGroup&gt;().HasIndex(p =&gt; p.Name).IsUnique().HasDatabaseName("Idx_Name");  
            modelBuilder.Entity&lt;User&gt;().HasIndex(u =&gt; u.FirstName).HasDatabaseName("Idx_FirstName");  
            modelBuilder.Entity&lt;User&gt;().HasIndex(u =&gt; u.LastName).HasDatabaseName("Idx_LastName");  
  
            // Configure columns  
            modelBuilder.Entity&lt;UserGroup&gt;().Property(ug =&gt; ug.Id).HasColumnType("int").UseMySqlIdentityColumn().IsRequired();  
            modelBuilder.Entity&lt;UserGroup&gt;().Property(ug =&gt; ug.Name).HasColumnType("nvarchar(100)").IsRequired();  
            modelBuilder.Entity&lt;UserGroup&gt;().Property(ug =&gt; ug.CreationDateTime).HasColumnType("datetime").IsRequired();  
            modelBuilder.Entity&lt;UserGroup&gt;().Property(ug =&gt; ug.LastUpdateDateTime).HasColumnType("datetime").IsRequired(false);  
  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.Id).HasColumnType("int").UseMySqlIdentityColumn().IsRequired();  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.FirstName).HasColumnType("nvarchar(50)").IsRequired();  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.LastName).HasColumnType("nvarchar(50)").IsRequired();  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.UserGroupId).HasColumnType("int").IsRequired();  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.CreationDateTime).HasColumnType("datetime").IsRequired();  
            modelBuilder.Entity&lt;User&gt;().Property(u =&gt; u.LastUpdateDateTime).HasColumnType("datetime").IsRequired(false);  
  
            // Configure relationships  
            modelBuilder.Entity&lt;User&gt;().HasOne&lt;UserGroup&gt;().WithMany().HasPrincipalKey(ug =&gt; ug.Id).HasForeignKey(u =&gt; u.UserGroupId).OnDelete(DeleteBehavior.NoAction).HasConstraintName("FK_Users_UserGroups");  
        }  
    }  
} </code></pre>



<p><strong>Step 6: Configure and inject the database connection</strong> </p>



<p>Configure the database connection string Add following database connection string codes in appsettings.json (you need to update the connection string with your server name, database name, port, user, or password)</p>



<pre class="wp-block-code"><code>{  
  "Logging": {  
    "LogLevel": {  
      "Default": "Information",  
      "Microsoft": "Warning",  
      "Microsoft.Hosting.Lifetime": "Information"  
    }  
  },  
  "AllowedHosts": "*",  
  "ConnectionStrings": {  
    "DefaultConnection": "server=localhost; port=3306; database=test; user=root; password=Wxp@Mysql; Persist Security Info=False; Connect Timeout=300"  
  }  
} </code></pre>



<p>Inject database connection In Startup.cs, add following codes,</p>



<pre class="wp-block-code"><code>using EFCoreMySQL.DBContexts;  
using Microsoft.EntityFrameworkCore;  
  
.  .  .  
  
        public void ConfigureServices(IServiceCollection services)  
        {  
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");  
            services.AddDbContextPool&lt;MyDBContext&gt;(options =&gt; options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));  
  
            services.AddControllers();  
        }  
  
.   .   .  </code></pre>



<p><strong>Step 7 &#8211; Create API Controllers</strong> </p>



<p>To show data on webpage, we need to have controllers. Let’s add simple controller files. </p>



<p>On VS 2019 Solution Explorer, right click folder “Controllers” &#8211; Add &#8211; Controller … Common &#8211; API Controller – Empty &#8211; Add &#8211; enter name: UserGroupController.cs &#8211; Add. </p>



<p><strong>UserGroupController.cs</strong></p>



<pre class="wp-block-code"><code>using EFCoreMySQL.DBContexts;  
using EFCoreMySQL.Models;  
using Microsoft.AspNetCore.Http;  
using Microsoft.AspNetCore.Mvc;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace EFCoreMySQL.Controllers  
{  
    [Route("api/[controller]")]  
    [ApiController]  
    public class UserGroupController : ControllerBase  
    {  
        private MyDBContext myDbContext;  
  
        public UserGroupController(MyDBContext context)  
        {  
            myDbContext = context;  
        }  
  
        [HttpGet]  
        public IList&lt;UserGroup&gt; Get()  
        {  
            return (this.myDbContext.UserGroups.ToList());  
        }  
    }  
}   </code></pre>



<p>On VS 2019 Solution Explorer, right click folder “Controllers” &#8211; Add &#8211; Controller … Common &#8211; API Controller – Empty &#8211; Add &#8211; enter name: UserController.cs &#8211; Add.</p>



<p><strong>UserController.cs</strong></p>



<pre class="wp-block-code"><code>using EFCoreMySQL.DBContexts;  
using EFCoreMySQL.Models;  
using Microsoft.AspNetCore.Http;  
using Microsoft.AspNetCore.Mvc;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace EFCoreMySQL.Controllers  
{  
    [Route("api/[controller]")]  
    [ApiController]  
    public class UserController : ControllerBase  
    {  
        private MyDBContext myDbContext;  
  
        public UserController(MyDBContext context)  
        {  
            myDbContext = context;  
        }  
  
        [HttpGet]  
        public IList&lt;User&gt; Get()  
        {  
            return (this.myDbContext.Users.ToList());  
        }  
    }  
}  </code></pre>



<p><strong>Step 8 &#8211; Add migration and update database</strong> </p>



<p>VS 2019 &#8211; Tools &#8211; NuGet Package Manager &#8211; Package Manager Console &#8211; run command “Add-Migration DBInit” &#8211; once done, run another command “Update-Database”.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="347" class="wp-image-2898 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-1.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-1-300x145.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-1-50x24.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Run MySQL Workbench, connect to the local MySQL server, we can see the database “test” along with two tables “UserGroups” and “Users” are already created automatically. </p>



<p>For testing purposes, we manually enter some records in these two tables on MySQL Workbench, so that we will see some data when we run this application.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="440" class="wp-image-2899 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-2.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-2-300x183.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Migration-2-50x31.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p><strong>Step 9 &#8211; Run application to test</strong> </p>



<p>On VS 2019 ribbon, click the drop-down as shown below, select “Google Chrome”, then select “IIS Express”. The dropdown will close and show “IIS Express”. Click “IIS Express” to build &amp; run for a test.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="147" class="wp-image-2900 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-1.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-1-300x61.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-1-50x10.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Enter https://localhost:44397/api/usergroup</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="259" class="wp-image-2901 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-2.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-2-300x108.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-2-50x18.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>Enter https://localhost:44397/api/user</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="720" height="259" class="wp-image-2902 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-3.png 720w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-3-300x108.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/Run-3-50x18.png 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-entity-framework-5-in-net-core-3-to-implement-code-first-approach/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
