1. Create a new ASP.NET Core Web Application project
2. Select Web API for template
3. Install the following packages from Nuget or Package Manager console:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.VisualStudio.Web.CodeGeneration.Design
4. On Package Manager console, run:
Scaffold-DbContext “Server=your_server_name;Database=your_db_name;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model
This will create DbContext instance and all the model classes for tables in database.
5. Open Startup.cs and comment out the whole OnConfiguring(DbContextOptionsBuilder optionsBuilder) method
6. On ConfigureServices(IServiceCollection services) method, add:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var connection = @"Server=server_name;Database=db_name;Trusted_Connection=True;ConnectRetryCount=0"; services.AddDbContext<MyDBContext>(options => options.UseSqlServer(connection)); }7. Create a controller by right clicking Controller folder
8. Choose ‘API Controller with actions, using Entity Framework’
9. Select a model class which you would like to use
For allowing CORS, put these codes on Startup.cs:
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()));
No comments:
Post a Comment