<?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 database migration &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/entity-framework-database-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 database 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>
	</channel>
</rss>
