Skip to content

Commit

Permalink
Merge pull request #1 from WKLD-Labs/EF-Core
Browse files Browse the repository at this point in the history
Prepare EF Core with SQLite and made Dummy Model and Controller
  • Loading branch information
misaalanshori authored May 12, 2024
2 parents d2b846c + 5fd9ea7 commit 273b322
Show file tree
Hide file tree
Showing 9 changed files with 312 additions and 1 deletion.
108 changes: 108 additions & 0 deletions csharp_backend/Controllers/DummiesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using csharp_backend;
using csharp_backend.Models;

namespace csharp_backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DummiesController : ControllerBase
{
private readonly LabsContext _context;

public DummiesController(LabsContext context)
{
_context = context;
}

// GET: api/Dummies
[HttpGet]
public async Task<ActionResult<IEnumerable<Dummy>>> GetDummies()
{
return await _context.Dummies.ToListAsync();
}

// GET: api/Dummies/5
[HttpGet("{id}")]
public async Task<ActionResult<Dummy>> GetDummy(int id)
{
var dummy = await _context.Dummies.FindAsync(id);

if (dummy == null)
{
return NotFound();
}

return dummy;
}

// PUT: api/Dummies/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutDummy(int id, Dummy dummy)
{
if (id != dummy.DummyId)
{
return BadRequest();
}

_context.Entry(dummy).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DummyExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return NoContent();
}

// POST: api/Dummies
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Dummy>> PostDummy(Dummy dummy)
{
_context.Dummies.Add(dummy);
await _context.SaveChangesAsync();

return CreatedAtAction("GetDummy", new { id = dummy.DummyId }, dummy);
}

// DELETE: api/Dummies/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteDummy(int id)
{
var dummy = await _context.Dummies.FindAsync(id);
if (dummy == null)
{
return NotFound();
}

_context.Dummies.Remove(dummy);
await _context.SaveChangesAsync();

return NoContent();
}

private bool DummyExists(int id)
{
return _context.Dummies.Any(e => e.DummyId == id);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions csharp_backend/Migrations/20240506035454_InitialCreateDummy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace csharp_backend.Migrations
{
/// <inheritdoc />
public partial class InitialCreateDummy : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Dummies",
columns: table => new
{
DummyId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
Value = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Dummies", x => x.DummyId);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Dummies");
}
}
}
46 changes: 46 additions & 0 deletions csharp_backend/Migrations/LabsContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using csharp_backend;

#nullable disable

namespace csharp_backend.Migrations
{
[DbContext(typeof(LabsContext))]
partial class LabsContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.4");

modelBuilder.Entity("csharp_backend.Models.Dummy", b =>
{
b.Property<int>("DummyId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");

b.Property<string>("Description")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("TEXT");

b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");

b.Property<string>("Value")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("TEXT");

b.HasKey("DummyId");

b.ToTable("Dummies");
});
#pragma warning restore 612, 618
}
}
}
29 changes: 29 additions & 0 deletions csharp_backend/Model.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using csharp_backend.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;

namespace csharp_backend
{
public class LabsContext : DbContext
{
// Define models here
public DbSet<Dummy> Dummies { get; set; }

public string DbPath { get; }

public LabsContext()
{
var folder = Environment.SpecialFolder.LocalApplicationData;
var path = Environment.GetFolderPath(folder);
path = System.IO.Path.Join(path, ".labsBackend");
System.IO.Directory.CreateDirectory(path);
DbPath = System.IO.Path.Join(path, "labsData.db");
}

// The following configures EF to create a Sqlite database file in the
// special "local" folder for your platform.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
}
23 changes: 23 additions & 0 deletions csharp_backend/Models/DummyModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace csharp_backend.Models
{
public class Dummy
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DummyId { get; set; }

[Required]
public string Name { get; set; }

[MaxLength(512)]
public string Description { get; set; }

[Required]
[MaxLength(128)]
public string Value { get; set; }

}
}
7 changes: 7 additions & 0 deletions csharp_backend/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

using Microsoft.EntityFrameworkCore;

namespace csharp_backend
{
public class Program
Expand All @@ -14,6 +16,9 @@ public static void Main(string[] args)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Register LabsContext service
builder.Services.AddDbContext<LabsContext>();

var app = builder.Build();

// Configure the HTTP request pipeline.
Expand All @@ -23,6 +28,8 @@ public static void Main(string[] args)
app.UseSwaggerUI();
}



app.UseHttpsRedirection();

app.UseAuthorization();
Expand Down
3 changes: 3 additions & 0 deletions csharp_backend/README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
# wkldLabs C# ASP.Net Core Web API Backend
Backend for wkldLabs using C#

## Getting Started with EF Core
This project uses EF Core SQLite for data access. Check out the following guide to get started: [Getting Started with EF Core](https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli)
12 changes: 11 additions & 1 deletion csharp_backend/csharp_backend.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
Expand All @@ -9,7 +9,17 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

Expand Down

0 comments on commit 273b322

Please sign in to comment.