Microsoft Azure – Creating SQL from scratch

It is my first impression with Azure and I must say that everything looks cool and easy. I have just created my test database in 5 miniutes!

Let me explain all step by step! (I wonโ€™t explain sign up ofcourse :))

First, click this,

Then we will create our resource and server, click on “Create Sql Database” button.

After this, we will wait for a while, Azure will generate these for us,

After everything completed, we can find our ConnectionString from here,

Copy this, we will use this in our test application ๐Ÿ™‚

Then let’s see our database, (click on query editor) and login with username and password!

It says we can’t login from this IP. We can add our IPv4 address like below,

After we did this, we can login without error,

Yes! Our database has been created! Easy right? ๐Ÿ™‚

Let’s write some code and feed this db! (I have created a .net 6 web api project)

Our table can be called as “Users” so we must have user entity,

public class TestUser
{
    [Key]
    public int Id { get; set; } 
    public string UserName { get; set; }
    public string Title { get; set; }
    public int Age { get; set; }
}

Giving[Key] data annotation will make that column as identity!

And also we should have a DbContext to access our database,

public class TestContext : DbContext
{
    public TestContext(DbContextOptions options) : base(options) { }

    public DbSet<TestUser> Users { get; set; } // our user table as DbSet
}

Now we need to give our connection string to this Context,

builder.Services.AddDbContext<TestContext>(x => x.UseSqlServer("theconnectionstringyouhavecopiedwillbehere"));

Final step! Let’s create a controller which will insert new User to our Azure DB,

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly TestContext testContext; 
    public UserController(TestContext _testContext) // resolved from IoC
    {
        testContext = _testContext;
    }

    [HttpPost("CreateUser")]
    public IActionResult CreateUser(TestUser myUser)
    {
        testContext.Database.EnsureCreated(); // this will create db if not exists
        testContext.Users.Add(myUser); // add our user to dbset
        return testContext.SaveChanges() > 0 ? Ok() : BadRequest();
    }
}

Here are the results,

Awesome ๐Ÿ™‚

Tags: