Getting Started with ASP.NET v.Next Beta 7

I wanted to document the steps I had to take to write an Web Api application with Entity Framework using beta 7 of ASP.NET v. next.  I already had previous beta installed.

First step is to update version manager (dnvm) runtime.  Just open Visual Studio command prompt and type the following

dnvm update-self

If this does not work, you can always manually download using the following powershell command

@powershell -NoProfile -ExecutionPolicy unrestricted -Command “&{$Branch=’dev’;iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1′))}”

You have to also update runtime.  If you want to see the list of installed runtimes, type dnvm list

To upgrade a runtime type the following

dnvm upgrade -arch x86 -runtime clr

You specify architecture and and runtime type, coreclr (cross platform runtime) or clr (windows runtime or current .NET runtime).  You can upgrade all the runtime, which is what I did.  Then I assigned an alias default to clr / x64 runtime.  If you want to lookup help for alias command, type dnvm help alias.

Now we can create new project.  In VS 2015 select new project from the menu and pick ASP.NET Web Application.  On the next prompt pick Web Api under ASP.NET 5 Preview Templates section.

SNAGHTML29086b78

Click OK to create the project.

The next step is redirect the runtime from the shipped template to the beta 7 runtime.  Open global.json file under solution items and make sure it has beta 7 in it.  If it does not, change it to the following.

{
  “projects”: [ “src”, “test” ],
  “sdk”: {
    “version”: “1.0.0-beta7”,
    “runtime”: “clr”,
    “architecture”: “x64”
  }
}

At this point you may not be able to build the solution due to NuGet packages not being properly restored.  To fix this issue, go to VS command prompt and switch to the folder for your new solution.  Make sure you are not in the solution folder, but in project folder, where project.json file is located.  Once you are in this folder, type the following.

dnvm use default

This will setup path to beta 7 runtime.  Make sure that your alias “default” is indeed pointing to beta 7 runtime.  To verify type dnvm list one more time.  Then type the following to restore NuGet packages.

dnu restore
Switch to Visual Studio and make sure you can build the solution.

Now it is time to add Entity Framework.  I am also going to add JSON based configuration packages.  Here is the full list of packages to add to project.json.

"dependencies": { "Microsoft.AspNet.Mvc": "6.0.0-beta7", "Microsoft.AspNet.Server.IIS": "1.0.0-beta7", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta7", "Microsoft.AspNet.StaticFiles": "1.0.0-beta7", "EntityFramework.Core": "7.0.0-beta7", "EntityFramework.Commands": "7.0.0-beta7", "EntityFramework.Relational": "7.0.0-beta7", "EntityFramework.SqlServer": "7.0.0-beta7", "EntityFramework.SqlServer.Design": "7.0.0-beta7", "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7", "Microsoft.Framework.Configuration": "1.0.0-beta7", "Microsoft.Framework.Configuration.Json": "1.0.0-beta7" },

Again, in my case Visual Studio failed to restore the packages.  So, back to command prompt and dnu restore.

Now I am going to add a class for my entity and DbContext.  My entity is very simple, it is a single Person class.

namespace WebApplication2.Data { public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }

My DbContext, database abstraction, will have a single DbSet for my Person class.

using Microsoft.Data.Entity; namespace WebApplication2.Data { public class PersonContext: DbContext { public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Person>().Property(c => c.FirstName).MaxLength(30); modelBuilder.Entity<Person>().Property(c => c.LastName).MaxLength(40); } } }

As you can see I also configured my column/properties.  In a large project I would break this code into its own class. Now I am going to experiment with JSON configuration files, as I failed to make that work in previous beta.  Just add new item to the project, and put in wwwroot folder, not root project folder.  Pick file template called ASP.NET configuration file.  The name should default to project.json.  It will have default connection string.  I changed mine to the following.

{ "Data": { "DefaultConnection": { "ConnectionString": "Server=.;Database=WebApp2;Trusted_Connection=True;" } } }

This assumes of course that I have SQL Server installed on my machine and logged in user (me) has admin rights on it to create a new database.  Now in startup.cs in the constructor I am going to setup my configuration.

public class Startup { public Startup(IHostingEnvironment env) { var jsonConfig = new JsonConfigurationSource(Path.Combine(env.WebRootPath, "config.json")); jsonConfig.Load(); IConfiguration configuration = new ConfigurationRoot(new IConfigurationSource[] { jsonConfig }); Configuration = configuration; } public IConfiguration Configuration { get; set; }

In my next step I can use this new configuration to setup EF connection.  This is done in ConfigureServices method in startup.cs.

public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddRelational() .AddSqlServer() .AddDbContext<PersonContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); }

In the next step we can look at migrations.  The code is slightly different from previous beta, but adding migrations is still the same.  First you need to add entity framework commands to commands section of project.json

"commands": { "web": "Microsoft.AspNet.Hosting --config hosting.ini", "ef": "EntityFramework.Commands" },

Next build the solution, then switch to command window.  Make sure you are in the project folder, not solution folder.  Type the following.

dnx migrations add initial

This will create initial migration in Migrations folder in your solution.  I did not have to specify context or project, since I only have one.  Build again to make sure everything is still cool.  Finally, we need to perform migrations at startup.  This is done in Configure method in startup.cs.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(); using (var cxt = (PersonContext)app.ApplicationServices.GetService(typeof(PersonContext))) { cxt.Database.Migrate(); } }

I am using dependency injection to get an instance of DbContext, pre-configured with specified connection string.  Then I use migrations API on Database object.

Now it is time to create a Web Api controller.  Create new class in Controllers folder (or any other folder for that matter).  My looks as follows.

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; using WebApplication2.Data; namespace WebApplication2.Controllers { [Route("api/[controller]")] public class PersonsController { private readonly PersonContext _personContext; public PersonsController(PersonContext personContext) { _personContext = personContext; } public async Task<IEnumerable<Person>> Get() { return await _personContext.People.OrderBy(p => p.FirstName) .ToListAsync() .ConfigureAwait(false); } } }

I just have a single method here, using async / await to make it asynchronous.  I am following best practices to allow the asynchronous code to run on with any context, not captured context, this is why I called ConfigureAwait(false).  I also use new route attribute, using new [controller] keyword as a substitute. Alternatively, I could have typed Route[“api/persons”], but I chose to let framework do more work for me.  I also did not specify a base controller, new Web Api works without base classes, just purely based on naming conventions.

I am ready to run the app now.

image

I am running using IIS Express.  Once browser is up, and I use Chrome, but you can use any browser, I type “api/persons” after port number, similarly to the following

http://localhost:18636/api/persons

You should see blank result and no errors.  Now you can open SQL Server management studio and see newly created database, WebApp2 in my case.  I can browse a few rows into Person table and refresh the browser to see my data.

Enjoy.  You can download the demo project here.

Leave a Reply

Your email address will not be published. Required fields are marked *