I was trying to connect to sql database from my asp.net core application in Angular 8. But as I am quite new to Angular it was feeling like a simple task being too complicated. Finally with help of multiple blogs and some UTube tutorials I was able to get the simple stuff working :)So here are the steps to get it done.
Step 1: Ensure your project have following nuget packages installed.
- Install-Package Microsoft.EntityFrameworkCore
- Install-Package Microsoft.EntityFrameworkCore.SqlServer
- Install-Package Microsoft.EntityFrameworkCore.Tools
Step 2: Create a connection String
Instead of app.config or web.config you are going to add this to appsettings.json file.
“ConnectionStrings” : {
“DevConnection” : “Server=MyServer;Database=dbName;UserId=;Password=;MultipleActiveResultSets=True;”
}
Step 3: Create a data context
This is a class generated from DbContext as in other project types
using Microsoft.EntityFrameworkCore;
namespace ApartmentManagement.CustomTypes
{
public class AmsDbContext : DbContext
{
public AmsDbContext(DbContextOptions<AmsDbContext> options) : base(options)
{
}
public DbSet<Tanent> Tanents { get; set; }
}
}
Step 4: Connect the datacontext with the connection string
This is done in Startup.cs file in function ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
//// Existing code
services.AddDbContext<AmsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
Step 5: Now create the model class
Step 6: Create normal web api controller class to serve for the CRUD operations
using ApartmentManagement.CustomTypes;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace ApartmentManagement.Controllers
{
[Route("[controller]")]
[ApiController]
public class TanentController : ControllerBase
{
private readonly AmsDbContext _context;
public TanentController(AmsDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<Tanent> Get()
{
//List<Tanent> tanentList = new List<Tanent>();
//tanentList.Add(new Tanent { Name = "Madhuri", FlatNumber = "E-1" });
//return tanentList.ToArray();
List<Tanent> tanentList = _context.Tanents.ToList<Tanent>();
return tanentList;
}
}
}
Congratulations !! You did it