Database creation into its own extension.

This commit is contained in:
JudahGabriel
2018-11-08 11:37:47 -06:00
parent 7669f27447
commit eb894a4db9
2 changed files with 52 additions and 21 deletions
+32
View File
@@ -0,0 +1,32 @@
using Raven.Client.Documents;
using Sample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sample.Extensions
{
public static class RavenExtensions
{
public static IDocumentStore EnsureExists(this IDocumentStore store)
{
try
{
using (var dbSession = store.OpenSession())
{
dbSession.Query<AppUser>().Take(0).ToList();
}
}
catch (Raven.Client.Exceptions.Database.DatabaseDoesNotExistException)
{
store.Maintenance.Server.Send(new Raven.Client.ServerWide.Operations.CreateDatabaseOperation(new Raven.Client.ServerWide.DatabaseRecord
{
DatabaseName = store.Database
}));
}
return store;
}
}
}
+20 -21
View File
@@ -12,6 +12,7 @@ using Sample.Models;
using Sample.Services;
using Raven.Identity;
using Raven.Client.Documents;
using Sample.Extensions;
namespace Sample
{
@@ -27,7 +28,6 @@ namespace Sample
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Connect to a Raven server. We're using the public test playground at http://live-test.ravendb.net
var databaseName = "Raven.Identity.Sample";
var docStore = new DocumentStore
@@ -35,8 +35,7 @@ namespace Sample
Urls = new string[] { "http://live-test.ravendb.net" },
Database = databaseName
};
docStore.Initialize();
CreateDatabaseIfNotExists(docStore, databaseName);
docStore.Initialize().EnsureExists();
// Add RavenDB and identity.
services
@@ -52,24 +51,6 @@ namespace Sample
services.AddMvc();
}
private void CreateDatabaseIfNotExists(IDocumentStore docStore, string databaseName)
{
try
{
using (var dbSession = docStore.OpenSession())
{
dbSession.Query<AppUser>().Take(0).ToList();
}
}
catch (Raven.Client.Exceptions.Database.DatabaseDoesNotExistException)
{
docStore.Maintenance.Server.Send(new Raven.Client.ServerWide.Operations.CreateDatabaseOperation(new Raven.Client.ServerWide.DatabaseRecord
{
DatabaseName = databaseName
}));
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
@@ -95,5 +76,23 @@ namespace Sample
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private void CreateDatabaseIfNotExists(IDocumentStore docStore, string databaseName)
{
try
{
using (var dbSession = docStore.OpenSession())
{
dbSession.Query<AppUser>().Take(0).ToList();
}
}
catch (Raven.Client.Exceptions.Database.DatabaseDoesNotExistException)
{
docStore.Maintenance.Server.Send(new Raven.Client.ServerWide.Operations.CreateDatabaseOperation(new Raven.Client.ServerWide.DatabaseRecord
{
DatabaseName = databaseName
}));
}
}
}
}