Skip to content

Commit 37b462a

Browse files
adding in memory database
1 parent f1b1ded commit 37b462a

File tree

9 files changed

+90
-75
lines changed

9 files changed

+90
-75
lines changed

SampleWebApiAspNetCore/Helpers/DynamicExtensions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ public static dynamic ToDynamic(this object value)
1111
IDictionary<string, object> expando = new ExpandoObject();
1212

1313
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
14+
{
1415
expando.Add(property.Name, property.GetValue(value));
16+
}
1517

1618
return expando as ExpandoObject;
1719
}

SampleWebApiAspNetCore/Middleware/MiddlewareExtensions.cs

Lines changed: 0 additions & 15 deletions
This file was deleted.

SampleWebApiAspNetCore/Program.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,37 @@
11
using Microsoft.AspNetCore;
22
using Microsoft.AspNetCore.Hosting;
3+
using Microsoft.Extensions.DependencyInjection;
4+
using Microsoft.Extensions.Logging;
5+
using SampleWebApiAspNetCore.Repositories;
6+
using SampleWebApiAspNetCore.Services;
7+
using System;
38

49
namespace WebApplication11
510
{
611
public class Program
712
{
813
public static void Main(string[] args)
914
{
10-
CreateWebHostBuilder(args).Build().Run();
15+
var host = CreateWebHostBuilder(args).Build();
16+
17+
// Initializes db.
18+
using (var scope = host.Services.CreateScope())
19+
{
20+
var services = scope.ServiceProvider;
21+
try
22+
{
23+
var context = services.GetRequiredService<FoodDbContext>();
24+
var dbInitializer = services.GetRequiredService<ISeedDataService>();
25+
dbInitializer.Initialize(context).GetAwaiter().GetResult();
26+
}
27+
catch (Exception ex)
28+
{
29+
var logger = services.GetRequiredService<ILogger<Program>>();
30+
logger.LogError(ex, "An error occurred while seeding the database.");
31+
}
32+
}
33+
34+
host.Run();
1135
}
1236

1337
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,48 @@
1+
using SampleWebApiAspNetCore.Entities;
2+
using SampleWebApiAspNetCore.Helpers;
3+
using SampleWebApiAspNetCore.Models;
14
using System;
2-
using System.Collections.Concurrent;
35
using System.Collections.Generic;
46
using System.Linq;
5-
using SampleWebApiAspNetCore.Entities;
6-
using SampleWebApiAspNetCore.Models;
77
using System.Linq.Dynamic.Core;
8-
using SampleWebApiAspNetCore.Helpers;
98

109
namespace SampleWebApiAspNetCore.Repositories
1110
{
12-
public class FoodRepository : IFoodRepository
11+
public class EfFoodRepository : IFoodRepository
1312
{
14-
private readonly ConcurrentDictionary<int, FoodItem> _storage = new ConcurrentDictionary<int, FoodItem>();
13+
private readonly FoodDbContext _foodDbContext;
14+
15+
public EfFoodRepository(FoodDbContext foodDbContext)
16+
{
17+
_foodDbContext = foodDbContext;
18+
}
1519

1620
public FoodItem GetSingle(int id)
1721
{
18-
FoodItem foodItem;
19-
return _storage.TryGetValue(id, out foodItem) ? foodItem : null;
22+
return _foodDbContext.FoodItems.FirstOrDefault(x => x.Id == id);
2023
}
2124

2225
public void Add(FoodItem item)
2326
{
24-
item.Id = !_storage.Values.Any() ? 1 : _storage.Values.Max(x => x.Id) + 1;
25-
26-
if (!_storage.TryAdd(item.Id, item))
27-
{
28-
throw new Exception("Item could not be added");
29-
}
27+
_foodDbContext.FoodItems.Add(item);
3028
}
3129

3230
public void Delete(int id)
3331
{
34-
FoodItem foodItem;
35-
if (!_storage.TryRemove(id, out foodItem))
36-
{
37-
throw new Exception("Item could not be removed");
38-
}
32+
FoodItem foodItem = GetSingle(id);
33+
_foodDbContext.FoodItems.Remove(foodItem);
3934
}
4035

4136
public FoodItem Update(int id, FoodItem item)
4237
{
43-
_storage.TryUpdate(id, item, GetSingle(id));
38+
_foodDbContext.FoodItems.Update(item);
4439
return item;
4540
}
4641

4742
public IQueryable<FoodItem> GetAll(QueryParameters queryParameters)
4843
{
49-
IQueryable<FoodItem> _allItems = _storage.Values.AsQueryable().OrderBy(queryParameters.OrderBy,
50-
queryParameters.IsDescending());
44+
IQueryable<FoodItem> _allItems = _foodDbContext.FoodItems.OrderBy(queryParameters.OrderBy,
45+
queryParameters.IsDescending());
5146

5247
if (queryParameters.HasQuery())
5348
{
@@ -61,6 +56,16 @@ public IQueryable<FoodItem> GetAll(QueryParameters queryParameters)
6156
.Take(queryParameters.PageCount);
6257
}
6358

59+
public int Count()
60+
{
61+
return _foodDbContext.FoodItems.Count();
62+
}
63+
64+
public bool Save()
65+
{
66+
return (_foodDbContext.SaveChanges() >= 0);
67+
}
68+
6469
public ICollection<FoodItem> GetRandomMeal()
6570
{
6671
List<FoodItem> toReturn = new List<FoodItem>();
@@ -72,22 +77,12 @@ public ICollection<FoodItem> GetRandomMeal()
7277
return toReturn;
7378
}
7479

75-
public int Count()
76-
{
77-
return _storage.Count;
78-
}
79-
80-
public bool Save()
81-
{
82-
// To keep interface consistent with Controllers, Tests & EF Interfaces
83-
return true;
84-
}
8580
private FoodItem GetRandomItem(string type)
8681
{
87-
return _storage.Values
82+
return _foodDbContext.FoodItems
8883
.Where(x => x.Type == type)
8984
.OrderBy(o => Guid.NewGuid())
9085
.FirstOrDefault();
9186
}
9287
}
93-
}
88+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using SampleWebApiAspNetCore.Entities;
3+
4+
namespace SampleWebApiAspNetCore.Repositories
5+
{
6+
public class FoodDbContext : DbContext
7+
{
8+
public FoodDbContext(DbContextOptions<FoodDbContext> options)
9+
: base(options)
10+
{
11+
12+
}
13+
14+
public DbSet<FoodItem> FoodItems { get; set; }
15+
16+
}
17+
}

SampleWebApiAspNetCore/SampleWebApiAspNetCore.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<Project Sdk="Microsoft.NET.Sdk.Web">
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.1</TargetFramework>
@@ -13,6 +13,7 @@
1313
<PackageReference Include="Microsoft.AspNetCore.App" />
1414
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.2.0" />
1515
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />
16+
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.1.0" />
1617
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.4.0" />
1718
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.9" />
1819
</ItemGroup>
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
using System.Threading.Tasks;
1+
using SampleWebApiAspNetCore.Repositories;
2+
using System.Threading.Tasks;
23

34
namespace SampleWebApiAspNetCore.Services
45
{
56
public interface ISeedDataService
67
{
7-
void EnsureSeedData();
8+
Task Initialize(FoodDbContext context);
89
}
910
}
Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
using SampleWebApiAspNetCore.Entities;
22
using SampleWebApiAspNetCore.Repositories;
33
using System;
4+
using System.Threading.Tasks;
45

56
namespace SampleWebApiAspNetCore.Services
67
{
78
public class SeedDataService : ISeedDataService
89
{
9-
IFoodRepository _repository;
10-
11-
public SeedDataService(IFoodRepository repository)
10+
public async Task Initialize(FoodDbContext context)
1211
{
13-
_repository = repository;
14-
}
12+
context.FoodItems.Add(new FoodItem() { Calories = 1000, Name = "Lasagne", Created = DateTime.Now });
13+
context.FoodItems.Add(new FoodItem() { Calories = 1100, Name = "Hamburger", Created = DateTime.Now });
14+
context.FoodItems.Add(new FoodItem() { Calories = 1200, Name = "Spaghetti", Created = DateTime.Now });
15+
context.FoodItems.Add(new FoodItem() { Calories = 1300, Name = "Pizza", Created = DateTime.Now });
1516

16-
public void EnsureSeedData()
17-
{
18-
_repository.Add(new FoodItem() { Calories = 1000, Id = 1, Name = "Lasagne", Created = DateTime.Now });
19-
_repository.Add(new FoodItem() { Calories = 1100, Id = 2, Name = "Hamburger", Created = DateTime.Now });
20-
_repository.Add(new FoodItem() { Calories = 1200, Id = 3, Name = "Spaghetti", Created = DateTime.Now });
21-
_repository.Add(new FoodItem() { Calories = 1300, Id = 4, Name = "Pizza", Created = DateTime.Now });
17+
await context.SaveChangesAsync();
2218
}
2319
}
2420
}

SampleWebApiAspNetCore/Startup.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Builder;
1+
using Microsoft.AspNetCore.Builder;
62
using Microsoft.AspNetCore.Diagnostics;
73
using Microsoft.AspNetCore.Hosting;
84
using Microsoft.AspNetCore.Http;
9-
using Microsoft.AspNetCore.HttpsPolicy;
105
using Microsoft.AspNetCore.Mvc;
116
using Microsoft.AspNetCore.Mvc.ApiExplorer;
127
using Microsoft.AspNetCore.Mvc.Infrastructure;
138
using Microsoft.AspNetCore.Mvc.Routing;
149
using Microsoft.AspNetCore.Mvc.Versioning;
10+
using Microsoft.EntityFrameworkCore;
1511
using Microsoft.Extensions.Configuration;
1612
using Microsoft.Extensions.DependencyInjection;
1713
using Microsoft.Extensions.Logging;
18-
using Microsoft.Extensions.Options;
1914
using SampleWebApiAspNetCore.Dtos;
2015
using SampleWebApiAspNetCore.Entities;
21-
using SampleWebApiAspNetCore.Middleware;
2216
using SampleWebApiAspNetCore.Repositories;
2317
using SampleWebApiAspNetCore.Services;
2418
using Swashbuckle.AspNetCore.Swagger;
@@ -38,7 +32,7 @@ public Startup(IConfiguration configuration)
3832
public void ConfigureServices(IServiceCollection services)
3933
{
4034
services.AddOptions();
41-
35+
services.AddDbContext<FoodDbContext>(opt => opt.UseInMemoryDatabase("FoodDatabase"));
4236
services.AddCors(options =>
4337
{
4438
options.AddPolicy("AllowAllOrigins",
@@ -52,7 +46,7 @@ public void ConfigureServices(IServiceCollection services)
5246
});
5347

5448
services.AddSingleton<ISeedDataService, SeedDataService>();
55-
services.AddSingleton<IFoodRepository, FoodRepository>();
49+
services.AddScoped<IFoodRepository, EfFoodRepository>();
5650
services.AddRouting(options => options.LowercaseUrls = true);
5751
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
5852
services.AddScoped<IUrlHelper>(implementationFactory =>
@@ -120,7 +114,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory,
120114
});
121115
}
122116

123-
app.AddSeedData();
117+
//app.AddSeedData();
124118

125119
app.UseHttpsRedirection();
126120

0 commit comments

Comments
 (0)