Using ASP.NET Core with MS SQL Server and Scaffolding on Linux
Published on: — Last updated on:This post assumes you have .NET Core SDK and Microsoft SQL Server installed on your machine. I'm using the latest version of .NET Core 1.1 (1.1.0-preview1-005077) and Microsoft SQL Server 2017 (RC1) on Ubuntu 17.04.
Creating a simple MVC app
Let's open the terminal and use the dotnet
command with Individual
authentication and LocalDB to have a nice boilerplate!
dotnet new mvc --auth Individual --use-local-db true -o BlogPost
Now, we just need to change the connection string inside appsettings.json
to
something like:
"DefaultConnection": "Server=localhost;Database=your-db-name;Trusted_Connection=False;MultipleActiveResultSets=true;user id=sa;password=your-sophisticated-password"
and Ta-Da! We can use MS SQL Server with ASP.NET Core on Linux! For more information about connection strings, consult SQL Server Connection Strings for ASP.NET Web Applications.
Scaffolding with aspnet-codegenerator
This version of .NET Core creates a .csproj
with the required NuGet packages
for scaffolding. Just run dotnet aspnet-codegenerator
and have fun with it :D
If you can't use the latest preview release, then you may want to add
System.Composition
, Microsoft.Composition
and
Microsoft.VisualStudio.Web.CodeGeneration.Design
packages to your project
using the following commands:
dotnet add package System.Composition
dotnet add package Microsoft.Composition
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
Finally, Run dotnet restore
followed by one of the following commands to see
the available options to scaffold your views, controllers and areas :)
dotnet aspnet-codegenerator view -h
dotnet aspnet-codegenerator controller -h
dotnet aspnet-codegenerator area -h
I found myself creating a model (Say Post.cs
) then executing the following
command to scaffold a controller, views and the data context:
dotnet aspnet-codegenerator controller -name PostsController -m BlogPost.Models.Post -dc BlogPost.Models.PostContext --relativeFolderPath Controllers -scripts --useDefaultLayout
For more information, see SO's How to generate controller using dotnetcore command line, SO's Reference .NET 4.5 dll in .NET Core 1.1 csproj? and Visual Studio Code extension: ASP.NET Core Scaffolding.
A side note: There's a ticket opened on GitHub to track documenting aspnet-codegenerator. Let's hope it'll be published soon! I hope this post was helpful to you :)