R
Join ServerRailway
✋|help
ASP.Net MVC 6 Deployment
Does anyone know how to deploy and ASP.Net MVC in Railway with a MySQL database?
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)
Cool will check it out
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
N/A
N/AS
N/A
Are you using the DATABASE_URL env var to connect?
Not really sure where to put that in my project
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"));
do you mean entity framework?
Yes
yup it saya 6.0.10
says*
Where are you initializing your DB connection?
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
Sure
1. You're trying to use SQL Server right now
options.UseSqlServer(builder.Configuration.GetConnectionString("TodoWebAppContext") ?? throw new InvalidOperationException("Connection string 'TodoWebAppContext' not found.")));
oh
What do I need to change?
First, add the
MySql.Data.EntityFramework
packageThen 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
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)
);
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();
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>
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.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)
)
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.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));
}
...
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>
I used
Pomelo.EntityFrameworkCore.MySql
since MySql.Data.EntityFramework
is deprecated.Great! No problem!