Unverified Commit d4e4b138 authored by Steve Smith's avatar Steve Smith Committed by GitHub

Adding Sqlite Support (#65)

* Ignore sqlite files

* Sqlite working with file in root of web

* All tests passing

* Cleaning up

* Ignore sqlite files

* Sqlite working with file in root of web

* All tests passing

* Cleaning up

* Updating packages
parent d8d86869
...@@ -249,4 +249,5 @@ paket-files/ ...@@ -249,4 +249,5 @@ paket-files/
# JetBrains Rider # JetBrains Rider
.idea/ .idea/
*.sln.iml *.sln.iml
\ No newline at end of file *.sqlite
...@@ -8,7 +8,7 @@ namespace CleanArchitecture.Core ...@@ -8,7 +8,7 @@ namespace CleanArchitecture.Core
{ {
public static int PopulateDatabase(IRepository todoRepository) public static int PopulateDatabase(IRepository todoRepository)
{ {
if (todoRepository.List<ToDoItem>().Any()) return 0; if (todoRepository.List<ToDoItem>().Count() >= 5) return 0;
todoRepository.Add(new ToDoItem todoRepository.Add(new ToDoItem
{ {
......
...@@ -17,5 +17,6 @@ ...@@ -17,5 +17,6 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" />
<PackageReference Include="SQLite" Version="3.13.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
...@@ -5,6 +5,7 @@ using CleanArchitecture.Core.Entities; ...@@ -5,6 +5,7 @@ using CleanArchitecture.Core.Entities;
using CleanArchitecture.Core.SharedKernel; using CleanArchitecture.Core.SharedKernel;
using Ardalis.EFCore.Extensions; using Ardalis.EFCore.Extensions;
using System.Reflection; using System.Reflection;
using JetBrains.Annotations;
namespace CleanArchitecture.Infrastructure.Data namespace CleanArchitecture.Infrastructure.Data
{ {
...@@ -12,6 +13,10 @@ namespace CleanArchitecture.Infrastructure.Data ...@@ -12,6 +13,10 @@ namespace CleanArchitecture.Infrastructure.Data
{ {
private readonly IDomainEventDispatcher _dispatcher; private readonly IDomainEventDispatcher _dispatcher;
//public AppDbContext(DbContextOptions options) : base(options)
//{
//}
public AppDbContext(DbContextOptions<AppDbContext> options, IDomainEventDispatcher dispatcher) public AppDbContext(DbContextOptions<AppDbContext> options, IDomainEventDispatcher dispatcher)
: base(options) : base(options)
{ {
...@@ -34,6 +39,9 @@ namespace CleanArchitecture.Infrastructure.Data ...@@ -34,6 +39,9 @@ namespace CleanArchitecture.Infrastructure.Data
{ {
int result = base.SaveChanges(); int result = base.SaveChanges();
// ignore events if no dispatcher provided
if (_dispatcher == null) return result;
// dispatch events only if save was successful // dispatch events only if save was successful
var entitiesWithEvents = ChangeTracker.Entries<BaseEntity>() var entitiesWithEvents = ChangeTracker.Entries<BaseEntity>()
.Select(e => e.Entity) .Select(e => e.Entity)
......
...@@ -29,6 +29,8 @@ ...@@ -29,6 +29,8 @@
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" PrivateAssets="All" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" PrivateAssets="All" />
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.0.76" /> <PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.0.76" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
<PackageReference Include="SQLite" Version="3.13.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.6"/>
</ItemGroup> </ItemGroup>
<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish"> <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
......
using Microsoft.AspNetCore; using CleanArchitecture.Infrastructure.Data;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
namespace CleanArchitecture.Web namespace CleanArchitecture.Web
{ {
...@@ -7,7 +12,27 @@ namespace CleanArchitecture.Web ...@@ -7,7 +12,27 @@ namespace CleanArchitecture.Web
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateWebHostBuilder(args).Build().Run(); var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<AppDbContext>();
// context.Database.Migrate();
context.Database.EnsureCreated();
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
} }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
......
using CleanArchitecture.Core.Entities; using CleanArchitecture.Core.Entities;
using CleanArchitecture.Infrastructure.Data; using CleanArchitecture.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace CleanArchitecture.Web namespace CleanArchitecture.Web
{ {
public static class SeedData public static class SeedData
{ {
public static readonly ToDoItem ToDoItem1 = new ToDoItem
{
Title = "Get Sample Working",
Description = "Try to get the sample to build."
};
public static readonly ToDoItem ToDoItem2 = new ToDoItem
{
Title = "Review Solution",
Description = "Review the different projects in the solution and how they relate to one another."
};
public static readonly ToDoItem ToDoItem3 = new ToDoItem
{
Title = "Run and Review Tests",
Description = "Make sure all the tests run and review what they are doing."
};
public static void Initialize(IServiceProvider serviceProvider)
{
using (var dbContext = new AppDbContext(
serviceProvider.GetRequiredService<DbContextOptions<AppDbContext>>(), null))
{
// Look for any TODO items.
if (dbContext.ToDoItems.Any())
{
return; // DB has been seeded
}
PopulateTestData(dbContext);
}
}
public static void PopulateTestData(AppDbContext dbContext) public static void PopulateTestData(AppDbContext dbContext)
{ {
var toDos = dbContext.ToDoItems; foreach (var item in dbContext.ToDoItems)
foreach (var item in toDos)
{ {
dbContext.Remove(item); dbContext.Remove(item);
} }
dbContext.SaveChanges(); dbContext.SaveChanges();
dbContext.ToDoItems.Add(new ToDoItem() dbContext.ToDoItems.Add(ToDoItem1);
{ dbContext.ToDoItems.Add(ToDoItem2);
Title = "Test Item 1", dbContext.ToDoItems.Add(ToDoItem3);
Description = "Test Description One"
});
dbContext.ToDoItems.Add(new ToDoItem()
{
Title = "Test Item 2",
Description = "Test Description Two"
});
dbContext.SaveChanges(); dbContext.SaveChanges();
} }
} }
} }
...@@ -35,8 +35,10 @@ namespace CleanArchitecture.Web ...@@ -35,8 +35,10 @@ namespace CleanArchitecture.Web
}); });
// TODO: Add DbContext and IOC // TODO: Add DbContext and IOC
string dbName = Guid.NewGuid().ToString(); string dbName = Guid.NewGuid().ToString();
services.AddDbContext<AppDbContext>(options => services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase(dbName)); options.UseSqlite("Data Source=database.sqlite")); // will be created in web project root
// options.UseInMemoryDatabase(dbName));
//options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc() services.AddMvc()
......
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
<handlers> <handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" /> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers> </handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" startupTimeLimit="3600" requestTimeout="23:00:00" /> <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" startupTimeLimit="3600" requestTimeout="23:00:00">
<environmentVariables />
</aspNetCore>
</system.webServer> </system.webServer>
</configuration> </configuration>
\ No newline at end of file
...@@ -26,9 +26,13 @@ namespace CleanArchitecture.Tests.Integration.Web.Api ...@@ -26,9 +26,13 @@ namespace CleanArchitecture.Tests.Integration.Web.Api
var stringResponse = await response.Content.ReadAsStringAsync(); var stringResponse = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<IEnumerable<ToDoItem>>(stringResponse).ToList(); var result = JsonConvert.DeserializeObject<IEnumerable<ToDoItem>>(stringResponse).ToList();
Assert.Equal(2, result.Count()); Assert.Equal(3, result.Count());
Assert.Equal(1, result.Count(a => a.Title == "Test Item 1")); Assert.Contains(result, i => i.Title == SeedData.ToDoItem1.Title);
Assert.Equal(1, result.Count(a => a.Title == "Test Item 2")); Assert.Contains(result, i => i.Title == SeedData.ToDoItem2.Title);
Assert.Contains(result, i => i.Title == SeedData.ToDoItem3.Title);
//Assert.Equal(1, result.Count(a => a == SeedData.ToDoItem1));
//Assert.Equal(1, result.Count(a => a == SeedData.ToDoItem2));
//Assert.Equal(1, result.Count(a => a == SeedData.ToDoItem3));
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment