ASP.Net MVC 6 Deployment

Does anyone know how to deploy and ASP.Net MVC in Railway with a MySQL database?
24 Replies
Percy
Percy2y ago
Please provide your project ID or reply with N/A. Thread will automatically be closed if no reply is received within 10 minutes. You can copy your project's id by pressing Ctrl/Cmd + K -> Copy Project ID.
Percy
Percy2y ago
⚠️ experimental feature
root
root2y ago
You should be able to add a MySQL database service and then deploy your code as usual. (Railway has built-in .NET support through Nixpacks, so you shouldn't need a Dockerfile or anything: https://nixpacks.com/docs/providers/csharp)
Kapatid
Kapatid2y ago
Cool will check it out
Percy
Percy2y ago
No project ID was provided. Closing thread.
Kapatid
Kapatid2y ago
I was able to able to deploy it but it fails to connect to my MySQL. I also noticed that it did not automatically generated a table when I added my Github repo
root
root2y ago
N/A N/AS N/A Are you using the DATABASE_URL env var to connect?
Kapatid
Kapatid2y ago
Not really sure where to put that in my project
root
root2y ago
Are you using EF6? the env var DATABASE_URL should be passed as the connection string Something like
MySqlConnection conn = new MySqlConnection(System.Environment.GetEnvironmentVariable("DATABASE_URL"));
MySqlConnection conn = new MySqlConnection(System.Environment.GetEnvironmentVariable("DATABASE_URL"));
Kapatid
Kapatid2y ago
do you mean entity framework?
root
root2y ago
Yes
Kapatid
Kapatid2y ago
yup it saya 6.0.10 says*
root
root2y ago
Where are you initializing your DB connection?
Kapatid
Kapatid2y ago
no sure about that because I always use code gen in Visual Studio do you want to take a look at my github repo? its just a todo app for practice
root
root2y ago
Sure
Kapatid
Kapatid2y ago
GitHub
GitHub - nadjitan/TodoWebApp: Simple todo web app usin asp.net mvc
Simple todo web app usin asp.net mvc. Contribute to nadjitan/TodoWebApp development by creating an account on GitHub.
root
root2y ago
1. You're trying to use SQL Server right now
options.UseSqlServer(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
options.UseSqlServer(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
Kapatid
Kapatid2y ago
oh What do I need to change?
root
root2y ago
First, add the MySql.Data.EntityFramework package Then replace UseSqlServer with UseMySql And replace the GetConnectionString call with System.Environment.GetEnvironmentVariable("DATABASE_URL") And see if that works (I'm afraid I haven't worked with .NET that much) All in Program.cs
Kapatid
Kapatid2y ago
Any help is appreciated and will now try your suggestions I noticed that in Railway they have a different version of MySQL. How do I turn this into their format?
CREATE TABLE [dbo].[Todo] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NULL,
[Done] BIT NOT NULL,
[CreatedDate] DATETIME2 (7) NOT NULL,
CONSTRAINT [PK_Todo] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Todo] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NULL,
[Done] BIT NOT NULL,
[CreatedDate] DATETIME2 (7) NOT NULL,
CONSTRAINT [PK_Todo] PRIMARY KEY CLUSTERED ([Id] ASC)
);
I tried doing this steps but nothing worked so I ended up with this code instead even though it still does not work. Program.cs
using Microsoft.EntityFrameworkCore;
using TodoWebApp.Data;

var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
}
else if (builder.Environment.IsProduction())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseSqlServer(Environment.GetEnvironmentVariable("DATABASE_URL")!));
}

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
using Microsoft.EntityFrameworkCore;
using TodoWebApp.Data;

var builder = WebApplication.CreateBuilder(args);

if (builder.Environment.IsDevelopment())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
}
else if (builder.Environment.IsProduction())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseSqlServer(Environment.GetEnvironmentVariable("DATABASE_URL")!));
}

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
I also needed to change my TodoWebApp.csproj file into this:
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!--Production-->
<PropertyGroup Condition="'$(Configuration)' != '' AND '$(Configuration)' != 'Debug'">
<InvariantGlobalization>true</InvariantGlobalization>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
</ItemGroup>

</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!--Production-->
<PropertyGroup Condition="'$(Configuration)' != '' AND '$(Configuration)' != 'Debug'">
<InvariantGlobalization>true</InvariantGlobalization>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
</ItemGroup>

</Project>
Kapatid
Kapatid2y ago
This is the error I get in my body when my app is deployed in Railway. I think that Environment.GetEnvironmentVariable("DATABASE_URL") is what keeps me from accessing my env variable even though I already created DATABASE_URL in my Variables.
root
root2y ago
1. Please use UseMySql instead of UseSqlServer 2. Here's an updated query; the one you sent isn't MySQL, it's SQL Server:
CREATE TABLE Todo (
Id INT NOT NULL AUTO_INCREMENT,
Title MEDIUMTEXT,
Done BOOL NOT NULL,
CreatedDate DATETIME NOT NULL
PRIMARY KEY (Id)
)
CREATE TABLE Todo (
Id INT NOT NULL AUTO_INCREMENT,
Title MEDIUMTEXT,
Done BOOL NOT NULL,
CreatedDate DATETIME NOT NULL
PRIMARY KEY (Id)
)
3. GetEnvironmentVariable isn't the problem. 4. Remove Microsoft.EntityFrameworkCore.SqlServer and replace it with MySql.Data.EntityFramework (in the csproj) 5. Set DOTNET_ENVIRONMENT=Production on Railway.
Kapatid
Kapatid2y ago
Ok I will try again Oh up until now I thought it was my version that is different Everything works now 😅. Thanks again for pointing out to get the env variables of Railway! Program.cs
var connectionString = "Server=localhost;Database=test;User=root;Password=;";
var serverVersion = new MySqlServerVersion(new Version(8, 0, 29));

...

if (builder.Environment.IsDevelopment())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
//options.UseMySQL(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
options.UseMySql(connectionString, serverVersion));
}
else if (builder.Environment.IsProduction())
{
var server = Environment.GetEnvironmentVariable("MYSQLHOST");
var db = Environment.GetEnvironmentVariable("MYSQLDATABASE");
var port = Environment.GetEnvironmentVariable("MYSQLPORT");
var user = Environment.GetEnvironmentVariable("MYSQLUSER");
var pass = Environment.GetEnvironmentVariable("MYSQLPASSWORD");

var prodConnection = $"server={server};database={db};port={port};user={user};password={pass};";

builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseMySql(prodConnection, serverVersion));
}

...
var connectionString = "Server=localhost;Database=test;User=root;Password=;";
var serverVersion = new MySqlServerVersion(new Version(8, 0, 29));

...

if (builder.Environment.IsDevelopment())
{
builder.Services.AddDbContext<TodoWebAppContext>(options =>
//options.UseMySQL(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
options.UseMySql(connectionString, serverVersion));
}
else if (builder.Environment.IsProduction())
{
var server = Environment.GetEnvironmentVariable("MYSQLHOST");
var db = Environment.GetEnvironmentVariable("MYSQLDATABASE");
var port = Environment.GetEnvironmentVariable("MYSQLPORT");
var user = Environment.GetEnvironmentVariable("MYSQLUSER");
var pass = Environment.GetEnvironmentVariable("MYSQLPASSWORD");

var prodConnection = $"server={server};database={db};port={port};user={user};password={pass};";

builder.Services.AddDbContext<TodoWebAppContext>(options =>
options.UseMySql(prodConnection, serverVersion));
}

...
TodoWebApp.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!--Production-->
<PropertyGroup Condition="'$(Configuration)' != '' AND '$(Configuration)' != 'Debug'">
<InvariantGlobalization>true</InvariantGlobalization>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
</ItemGroup>

</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!--Production-->
<PropertyGroup Condition="'$(Configuration)' != '' AND '$(Configuration)' != 'Debug'">
<InvariantGlobalization>true</InvariantGlobalization>
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
</ItemGroup>

</Project>
I used Pomelo.EntityFrameworkCore.MySql since MySql.Data.EntityFramework is deprecated.
root
root2y ago
Great! No problem!