One of the main new features of ASP.NET 5 is unifying the programming model and combining MVC, Web API, and Web Pages in single framework called MVC 6. In previous versions of ASP.NET (MVC 4, and MVC 5) there were overlapping in the features between MVC and Web API frameworks, but the concrete implementation for both frameworks was totally different, with ASP.NET 5 the merging between those different frameworks will make it easier to develop modern web applications/HTTP services and increase code reusability.
The source code for this tutorial is available on GitHub.
Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7
In this post I’ve decided to give ASP.NET 5 – MVC 6 Web API a test drive, I’ll be building a very simple RESTful API from scratch by using MVC 6 Web API and the new Entity Framework 7, so we will learn the following:
- Using the ASP.NET 5 empty template to build the Web API from scratch.
- Overview of the new project structure in VS 2015 and how to use the new dependency management tool.
- Configuring ASP.NET 5 pipeline to add only the components needed for our Web API.
- Using EF 7 commands and the K Version Manager (KVM) to initialize and apply DB migrations.
To follow along with this post you need to install VS 2015 preview edition or you can provision a virtual machine using Azure Images as they have an Image with VS 2015 preview installed.
Step 1: Creating an empty web project
Open VS 2015 and select New Web Project (ASP.NET Web Application) as the image below, do not forget to set the .NET Framework to 4.5.1. You can name the project “Registration_MVC6WebApi”.
Now we’ll select the template named “ASP.NET 5 Empty” as the image below, this template is an empty template with no core dependencies on any framework.
Step 2: Adding the needed dependencies
Once the project is created you will notice that there is a file named “project.json” this file contains all your project settings along with a section for managing project dependencies on other frameworks/components.
We’ve used to manage packages/dependencies by using NuGet package manager, and you can do this with the new enhanced NuGet package manager tool which ships with VS 2015, but in our case we’ll add all the dependencies using the “project.json” file and benefit from the IntelliSense provided as the image below:
So we will add the dependencies needed to configure our Web API, so open file “project.json” and replace the section “dependencies” with the section below:
1 2 3 4 5 6 7 8 9 |
"dependencies": { "Microsoft.AspNet.Server.IIS": "1.0.0-beta1", "EntityFramework": "7.0.0-beta1", "EntityFramework.SqlServer": "7.0.0-beta1", "EntityFramework.Commands": "7.0.0-beta1", "Microsoft.AspNet.Mvc": "6.0.0-beta1", "Microsoft.AspNet.Diagnostics": "1.0.0-beta1", "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta1" } |
The use for each dependency we’ve added as the below:
- Microsoft.AspNet.Server.IIS: We want to host our Web API using IIS, so this package is needed. If you are planning to self-host your Web API then no need to add this package.
- EntityFramework & EntityFramework.SqlServer: Our data provider for the Web API will be SQL Server. Entity Framework 7 can be configured to work with different data providers and not only relational databases, the data providers supported by EF 7 are: SqlServer, SQLite, AzureTableStorage, and InMemory. More about EF 7 data providers here.
- EntityFramework.Commands: This package will be used to make the DB migrations command available in our Web API project by using KVM, more about this later in the post.
- Microsoft.AspNet.Mvc: This is the core package which adds all the needed components to run Web API and MVC.
- Microsoft.AspNet.Diagnostics: Basically this package will be used to display a nice welcome page when you request the base URI for the API in a browser. You can ignore this if you want, but it will be nice to display welcoming page instead of the 403 page displayed for older Web API 2.
- Microsoft.Framework.ConfigurationModel.Json: This package is responsible to load and read the configuration file named “config.json”. We’ll add this file in a later step. This file is responsible to setup the “IConfiguration” object. I recommend to read this nice post about ASP.NET 5 new config files.
Last thing we need to add to the file “project.json” is a section named “commands” as the snippet below:
1 2 3 |
"commands": { "ef": "EntityFramework.Commands" } |
We’ve added short prefix “ef” for EntityFramework.Commands which will allow us to write EF commands such as initializing and applying DB migrations using KVM.
Step 3: Adding config.json configuration file
Now right click on your project and add new item of type “ASP.NET Configuration File” and name it “config.json”, you can think of this file as a replacement for the legacy Web.config file, for now this file will contain only our connection string to our SQL DB, I’m using SQL Express here and you can change this to your preferred SQL server.
1 2 3 4 5 6 7 |
{ "Data": { "DefaultConnection": { "Connectionstring": "Data Source=.\\sqlexpress;Initial Catalog=RegistrationDB;Integrated Security=True;" } } } |
Note: This is a JSON file that’s why we are using escape characters in the connection string.
Step 4: Configuring the ASP.NET 5 pipeline for our Web API
This is the class which is responsible for adding the components needed in our pipeline, currently with the ASP.NET 5 empty template, the class is empty and our web project literally does nothing, I’ll add all the code in our Startup class at once then describe what each line of code is responsible for, so open file Startup.cs and paste the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Hosting; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Registration_MVC6WebApi.Models; namespace Registration_MVC6WebApi { public class Startup { public static IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables(); } public void ConfigureServices(IServiceCollection services) { // Add EF services to the services container. services.AddEntityFramework().AddSqlServer().AddDbContext<RegistrationDbContext>(); services.AddMvc(); //Resolve dependency injection services.AddScoped<IRegistrationRepo, RegistrationRepo>(); services.AddScoped<RegistrationDbContext, RegistrationDbContext>(); } public void Configure(IApplicationBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 app.UseMvc(); app.UseWelcomePage(); } } } |
What we’ve implemented in this class is the following:
- The constructor for this class is responsible to read the settings in the configuration file “config.json” that we’ve defined earlier, currently we have only the connection string. So the static object “Configuration” contains this setting which we’ll use in the coming step.
- The method “ConfigureServices” accepts parameter of type “IServiceCollection”, this method is called automatically when starting up the project, as well this is the core method responsible to register components in our pipeline, so the components we’ve registered are:
- We’ve added “EntityFramework” using SQL Server as our data provider for the database context named “RegistrationDBContext”. We’ll add this DB context in next steps.
- Added the MVC component to our pipeline so we can use MVC and Web API.
- Lastly and one of the nice out of the box features which has been added to ASP.NET 5 is Dependency Injection without using any external IoC containers, notice how we are creating
single instancescoped instance of our “IRegistrationRepo” by calling services.AddScoped<IRegistrationRepo, RegistrationRepo>();. This instance will be available for theentire lifetime of our applicationlife time of the request, we’ll implement the classes “IRegistrationRepo” and “RegistrationRepo” in next steps of this post. There is a nice post about ASP.NET 5 dependency injection can be read here. (Update by Nick Nelson to use Scoped injection instead of using Singleton instance because DbContext is not thread safe).
- Lastly the method “Configure” accepts parameter of type “IApplicationBuilder”, this method configures the pipeline to use MVC and show the welcome page. Do not ask me why we have to call “AddMvc” and “UseMvc” and what is the difference between both 🙂 I would like to hear an answer if someone knows the difference or maybe this will be changed in the coming release of ASP.NET 5. (Update: Explanation of this pattern in the comments section).
Step 5: Adding Models, Database Context, and Repository
Now we’ll add a file named “Course” which contains two classes: “Course” and “CourseStatusModel”, those classes will represents our domain data model, so for better code organizing add new folder named “Models” then add the new file containing the the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.ComponentModel.DataAnnotations; namespace Registration_MVC6WebApi.Models { public class Course { public int Id { get; set; } [Required] [StringLength(100, MinimumLength = 5)] public string Name { get; set; } public int Credits { get; set; } } public class CourseStatusModel { public int Id { get; set; } public string Description { get; set; } } } |
Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “RegistrationDbContext” then paste the code snippet below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using Microsoft.Data.Entity; using System; using Microsoft.Data.Entity.Metadata; namespace Registration_MVC6WebApi.Models { public class RegistrationDbContext :DbContext { public DbSet<Course> Courses { get; set; } protected override void OnConfiguring(DbContextOptions options) { options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString")); } } } |
Basically what we’ve implemented here is adding our Courses data model as DbSet so it will represent a database table once we run the migrations, note that there is a new method named “OnConfiguration” where we can override it so we’ll be able to specify the data provider which needs to work with our DB context.
In our case we’ll use SQL Server, the constructor for “UseSqlServer” extension method accepts a parameter of type connection string, so we’ll read it from our “config.json” file by specifying the key “Data:DefaultConnection:ConnectionString” for the “Configuration” object we’ve created earlier in Startup class.
Note: This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.
Lastly we need to add the interface “IRegistrationRepo” and the implementation for this interface “RegistrationRepo”, so add two new files under “Models” folder named “IRegistrationRepo” and “RegistrationRepo” and paste the two code snippets below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections; using System.Collections.Generic; namespace Registration_MVC6WebApi.Models { public interface IRegistrationRepo { IEnumerable<Course> GetCourses(); Course GetCourse(int courseId); Course AddCourse(Course course); bool DeleteCourse(int courseId); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using System; using System.Collections.Generic; using System.Linq; namespace Registration_MVC6WebApi.Models { public class RegistrationRepo : IRegistrationRepo { private readonly RegistrationDbContext _db; public RegistrationRepo(RegistrationDbContext db) { _db = db; } public Course AddCourse(Course course) { _db.Courses.Add(course); if (_db.SaveChanges() > 0) { return course; } return null; } public bool DeleteCourse(int courseId) { var course = _db.Courses.FirstOrDefault(c => c.Id == courseId); if (course != null) { _db.Courses.Remove(course); return _db.SaveChanges() > 0; } return false; } public Course GetCourse(int courseId) { return _db.Courses.FirstOrDefault(c => c.Id == courseId); } public IEnumerable<Course> GetCourses() { return _db.Courses.AsEnumerable(); } } } |
The implementation here is fairly simple, what worth noting here is how we’ve passed “RegistrationDbContext” as parameter for our “RegistrationRepo” constructor so we’ve implemented Constructor Injection, this will not work if we didn’t configure this earlier in our “Startup” class.
Step 6: Installing KVM (K Version Manager)
After we’ve added our Database context and our domain data models, we can use migrations to create the database, with previous version of ASP.NET we’ve used NuGet package manager for these type of tasks, but with ASP.NET 5 we can use command prompt using various K* commands.
What is KVM (K Version Manager)? KVM is a Powershell script used to get the runtime and manage multiple versions of it being on the machine at the same time, you can read more about it here.
Now to install KVM for the first time you have to do the following steps:
1. Open a command prompt with Run as administrator.
2. Run the following command:
1 |
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))" |
3. The script installs KVM for the current user.
4. Exit the command prompt window and start another as an administrator (you need to start a new command prompt to get the updated path environment).
5. Upgrade KVM with the following command:
1 |
KVM upgrade |
We are ready now to run EF migrations as the step below:
Step 7: Initializing and applying migrations for our database
Now our command prompt is ready to understand K commands and Entity Framework commands, first step to do is to change the directory to the project directory. The project directory contains the “project.json” file as the image below:
So in the command prompt we need to run the 2 following commands:
1 2 |
k ef migration add initial k ef migration apply |
Basically the first command will add migration file with the name format (<date>_<migration name>) so we’ll end up having file named “201411172303154_initial.cs” under folder named “Migrations” in our project. This auto generated file contains the code needed to to add our Courses table to our database, the newly generated files will show up under your project as the image below:
The second command will apply those migrations and create the database for us based on the connection string we’ve specified earlier in file “config.json”.
Note: the “ef” command comes from the settings that we’ve specified earlier in file “project.json” under section “commands”.
Step 8: Adding GET methods for Courses Controller
The controller is a class which is responsible to handle HTTP requests, with ASP.NET 5 our Web API controller will inherit from “Controller” class not anymore from “ApiController”, so add new folder named “Controllers” then add new controller named “CoursesController” and paste the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using Microsoft.AspNet.Mvc; using Registration_MVC6WebApi.Models; using System; using System.Collections.Generic; namespace Registration_MVC6WebApi.Controllers { [Route("api/[controller]")] public class CoursesController : Controller { private IRegistrationRepo _registrationRepo; public CoursesController(IRegistrationRepo registrationRepo) { _registrationRepo = registrationRepo; } [HttpGet] public IEnumerable<Course> GetAllCourses() { return _registrationRepo.GetCourses(); } [HttpGet("{courseId:int}", Name = "GetCourseById")] public IActionResult GetCourseById(int courseId) { var course = _registrationRepo.GetCourse(courseId); if (course == null) { return HttpNotFound(); } return new ObjectResult(course); } } } |
What we’ve implemented in the controller class is the following:
- The controller is attribute with Route attribute as the following [Route("api/[controller]")] so any HTTP requests that match the template are routed to the controller. The “[controller]” part in the template URL means to substitute the controller class name, minus the “Controller” suffix. In our case and for “CoursesController” class, the route template is “api/courses”.
- We’ve defined two HTTP GET methods, the first one “GetAllCourses” is attributed with “[HttpGet]” and it returns a .NET object which is serialized in the body of the response using the default JSON format.
- The second HTTP GET method “GetCourseById” is attributed with “[HttpGet]“. For this method we’ve specified a constraint on the parameter “courseId”, the parameter should be of integer data type. As well we’ve specified a name for this method “GetCourseById” which we’ll use in the next step. Last thing this method returns object of type IActionResult which gives us flexibility to return different actions results based on our logic, in our case we will return HttpNotFound if the course does not exist or we can return serialized JSON object of the course when the course is found.
- Lastly notice how we are passing the “IRegistrationRepo” as a constructor for our CoursesController, by doing this we are implementing Constructor Injection.
Step 9: Adding POST and DELETE methods for Courses Controller
Now we want to implement another two HTTP methods which allow us to add new Course or delete existing one, so open file “CoursesController” and paste the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
[HttpPost] public IActionResult AddCourse([FromBody] Course course) { if (!ModelState.IsValid) { Context.Response.StatusCode = 400; return new ObjectResult(new CourseStatusModel { Id = 1 , Description= "Course model is invalid" }); } else { var addedCourse = _registrationRepo.AddCourse(course); if (addedCourse != null) { string url = Url.RouteUrl("GetCourseById", new { courseId = course.Id }, Request.Scheme, Request.Host.ToUriComponent()); Context.Response.StatusCode = 201; Context.Response.Headers["Location"] = url; return new ObjectResult(addedCourse); } else { Context.Response.StatusCode = 400; return new ObjectResult(new CourseStatusModel { Id = 2, Description = "Failed to save course" }); } } } |
What we’ve implemented here is the following:
- For method “AddCourse”:
- Add new HTTP POST method which is responsible to create new Course, this method accepts Course object which is coming from the request body then Web API framework will deserialize this to CLR Course object.
If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code and an object containing description of the validation error.Thanks for Yishai Galatzer for spotting this out because I was originally returning response of type “text/plain” always regarding the “Accept” header value set by the client. The point below contains the fix.- If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code, and in the response body we’ll return an instance of a POCO class(CourseStatusModel) containing fictional Id and description of the validation error.
- If the course created successfully then we’ll build a location URI which points to our new created course i.e. (/api/courses/4) and set this URI in the “Location” header for the response.
- Lastly we are returning the created course object in the response body.
- For method “DeleteCourse”:
- Add new HTTP DELETE method which is responsible for deleting existing course, this method accepts integer courseId.
- If the course has been deleted successfully we’ll return HTTP status 204 (No content)
- If the passed courseId doesn’t exists we will return HTTP status 404.
Note: I believe that the IhttpActionResult response which got introduced in Web API 2 is way better than IActionResult, please drop me a comment if someone knows how to use IhttpActionResult with MVC6.
The source code for this tutorial is available on GitHub.
That’s all for now folks! I’m still learning the new features in ASP.NET 5, please drop me a comment if you have better way implementing this tutorial or you spotted something that could be done in a better way.
From my understanding,
AddMvc is like requiring the assembly,
UseMvc is putting the Mvc in the pipeline actually making requests coming through your controllers.
I don’t know why one would want to use one without the other, but I guess this is the result of decoupling.
Ahhh that’s sound logical now, yes I do not find use case for using one without the other.
Thanks for an awesome blog!
Some comments:
The reason you call UseMvc separately than AddMvc is that AddMvc is where the MVC core services are added to the Dependency Injection system, and UseMvc is where MVC (specifically the routing middleware) is added to the pipeline.
Since DI registration has to be completed before services can be consumed, the registration is broken into two steps.
About IHttpActionResult – We are tracking two issues at the moment for improving action results for Web API scenarios.
1. Adding more ActionResults methods on the controller – https://github.com/aspnet/Mvc/issues/1378
2. Improving the pattern – https://github.com/aspnet/Mvc/issues/657
Feel free to respond here or comment on the issues.
Thank Yishai for taking the time to read the post and for the clarifications.
Now calling UseMvc and AddMvc separately makes sense.
I’ve received a comment from David Fowler earlier today that there are minor issues on the code, you were able to spot them?
Please let me know if you find any so I can update the post.
Here is what I see, David might have seen something different, you will have to ask him 🙂
When you return the following:
Context.Response.StatusCode = 400;
return new ObjectResult(“Failed to save course”);
You are really not returning Json or a String, instead you ask the content negotiation system to negotiate the result for you. By default this will return a text/plain content type with the string you passed. That’s not a typical approach for writing an API.
So if you want to return Json only, make a POCO class describing the error (say CourseStatus ??) and
Return JsonResult(new CourseStatus(“Failed to save course”));
if you want to always return a string regardless of how the Formatters are set up then you can just return ContentResult(“Failed to save course”);
Another thing to remember (and that is supported in Web API 2.x as well) is that you can just return an object from your method, and can mix objects and action results.
For example:
[HttpGet]
public object GetCourse(int id)
{
var course = await _repository.FindCourse(id);
if (course == null)
{
return HttpNotFound();
}
else
{
return course;
}
}
In regards to the usage of action results in your code when you have to set headers and status code before returning the action result itself I believe resolving issue#1 with some more love will prevent the need to setting these extra values. I’m just going to reference this blog in the issue to make sure we covered these scenarios.
@Yishai there was a discussion on Twitter the other day about AddMvc, UseMvc. I think the general sentiment is that one should implicitly cause other to happen. I believe the best solution would be to add a route lambda to AddMvc so that everything MVC specific is configured in one place, and with such setup UseMvc should be called implicitly by the framework and pass that route lambda
Opt in with UseMvc is too verbose IMHO, because 99,9% cases people opt in anyway.
https://twitter.com/filip_woj/status/534278917906251776
I don’t really agree. In a demoware app yes it will work. In anything real it will not.
Examples
– I want to explicitly chain another middleware ahead of MVC.
– I want to register more services after MVC.
I somewhat agree that we can consider moving the route configuration into AddMvc, and then the empty UseMvc just picks it up from there.
Thanks Filip for taking the time to read the post, interesting discussion indeed.
Thanks Again Yishai for your comprehensive feedback, post and code sample have been updated.
السلام عليكم …
اذا تسمح لي بترجمة المقالة الى اللغة العربية ونشرها بأسمك في منتدى فيجوال بيسك لكل العرب وكذلك مدونتي الشخصية ؟
للأسف لم استطع ارسال ايميل لك بهذا الخصوص .
بانتضار ردك
محبتي وتحياتي
المهندس محمد الساعدي
Alykom alsalam Mohammed,
No problem as long you reference my original blog and state that it is a translation of an original work.
Good luck 🙂
yes of course
Thank u
Nice article, but I think you should be registering your DbContext as Scoped not Singleton. I think these lines:
services.AddSingleton();
services.AddSingleton();
should be replaced by:
services.AddScoped();
services.AddScoped();
This has a decent explanation of lifestyles:
http://www.khalidabuhakmeh.com/asp-vnext-dependency-injection-lifecycles
EF6 (and I am assuming EF7) dbcontexts are not thread safe, so registering as a Singleton could cause some pretty weird errors if multiple people hit the WebAPI at once.
I think that the repository also has to be registered as Scoped, otherwise you would get one global instance of the repository that has the same instance of the DbContext even though it as registered as Scoped.
Hopefully some experts can educate us as to the proper registration pattern.
Sorry, I couldn’t help but test it out and it looks like they need to be scoped instead of singleton. See my pull request here: https://github.com/tjoudeh/JumpStart-MVC6WebApi/pull/1
Also, sorry for putting the other suggested changes of using localDB and adding a readme.md into that pull request. I was too lazy to go back and split them out into separate requests.
Thank you Nick, i’ll check the pull request and update the post to keep it in sync with code repo
Cool article! Please let me show you my article about DI in ASP.NET vNext: http://robinsedlaczek.wordpress.com/2014/11/22/dependency-injection-in-asp-net-vnext/
Thanks for sharing, I’ll read it once I’m at home 🙂
amazing tutorial ! thank you
Thanks Melih, glad you liked it 🙂
This sure was another interesting one to read and experiment with. Concise and straight forward as usual.
Given comments and opinions were also taken into accounts in my case. Thanks
So I’ve done my tests and managed to achieve what I wanted [got the results I expected… and most of the infos I needed… You were right about EF 7 ; )]
BTW Visual Studio 2015 CTP version is now available on line. It’s downloaded though I haven’t got time to install yet.
Anyone has worked with the new CTP version yet?
I am getting this error in mvc6 :
No parameterless constructor defined for this object.
And I have seen DefaultControllerFactory. It does not contain virtual methods to overrride.
Hi Sumit,
I’m not sure what version of MVC6 you are using now, there are lot of changes happening on the MVC6. But if you tried to download my repo it should work without any issues.
Dear Taiseer,
Your tutorials have been instrumental for me in becoming acclimated with so many new technologies, such as your Token Authorization series and now this great stuff on ASP MVC 6 and EF7. Keep up the good work…PLEASE!!
Thanks Sam for your nice message, really glad to know that my posts are useful, will do my best to keep those posts coming 🙂 Thanks again!
Did you realize your HTTP DELETE method is not shown here?
That’s amazing. I like all technologies of .NET.
Thanks Taiseer Joudeh very much.
You are welcome, glad to know posts are useful 🙂
Apparently the shim has IHttpActionResult:
See http://www.strathweb.com/2015/01/migrating-asp-net-web-api-mvc-6-exploring-web-api-compatibility-shim/
Great article, one of the best around about new .NET stuff.
About your note “This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.”
It was happening to me that I was getting a compilation on UseSqlServer on Startup.cs but was able fix it by adding the reference to Microsoft.Data.Entity (using Microsoft.Data.Entity; at the begining of the file) so maybe that was the reason the optimal way didn’t work for you.
so the ConfigureServices method ended up like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext(options =>
options.UseSqlServer(Configuration.Get(“Data:DefaultConnection:ConnectionString”)));
}
Hope it helps.
Thanks for sharing Nicolas, lot of changes is happening in ASP.NET 5 so yah I expect other way to implement the same feature.
Having forked the source code locally and opened the solution, the dependency restore causes “dnx.exe has stopped working” app crash dialogs which repeat ad infinitum.
I’ve tracked it down to the restore of EntityFramework.Commands for Asp.Net Core 5.0
How can I fix that?
I think I’ve just answered my question: upgrading to the latest version of the package has fixed the problem.
No problem 🙂
Use DbContextOptionsBuilder if using VS2015 RC like this
protected override void OnConfiguring(DbContextOptionsBuilder options)
VR_Architect
K has been replaces by DNX in the latest VS2015 build with a slightly different syntax, see for example: http://www.bricelam.net/2014/09/14/migrations-on-k.html
Hi Arni, you are right, the post is bit outdated now.
When I clone the Github source and try open it in Visual Studio 2015 I get a number of errors pertaining to IConfiguration and IConfigurationSouceContainer. This error in particular is a problem:
The type ‘IConfigurationSourceContainer’ is defined in an assembly that is not referenced. You must add a reference to the assembly ‘Microsoft.Framework.ConfigurationModel.IConfigurationSourceContainer, version 0.0.0.0, Culture=neutral, PublicKeyToken=null’
Any advice on how to fix this issue?
I need to download VS 2015 and check those errors, I have no answer now as I didn’t try it, if you solved it out then please share your findings here.
Do you can show us how to implement a token authentication in a Web API with ASP.NET 5 using the current technologies?
Thans
This is something, I’m going to work on after RC2. so maybe in February I will blog about this.
Great tutorial, really got me started, however, I ran into nothing but problems because of DNX and new versions of pretty much everything to rc1-final. Any chance of an update?
Project does no longer compile, automatic fix by VS 2015 creates errors without any known solution.
This is very old post with a lot of changes, I do not recommend depend on it as there are many other newer versions of asp.net core 1.0