mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.45k stars 1.23k forks source link

[QUESTION] Find if database exists and seed data after being created #1640

Closed mdmoura closed 4 years ago

mdmoura commented 4 years ago

When using the following:

using(var db = new LiteDatabase(@"MyData.db"))
}

LiteDB creates a new database if it does not exist.

Is there a way to determine if a database exists or not? Or if it is empty?

I would like to seed the database with data but only after its creation.

lbnascimento commented 4 years ago

@mdmoura I think something like this would work for you:

using(var db = new LiteDatabase(@"MyData.db"))
{
    int colCount = db.GetCollectionNames().Count();
    if (colCount == 0)
    {
        //initialization code here
    }
}
mdmoura commented 4 years ago

@lbnascimento I have been reading your docs and I found different information.

For example, in here there is an OnVersionUpdate method and a version can be included in the connection string.

But in source code and in here there is no such option.

I am trying the following to seed initial data:

 public class Database : LiteDatabase {

    public Database(String connectionString, DatabaseMapper databaseMapper) : base (connectionString, databaseMapper) { 

      if (base.UserVersion == 0) {
        // seed initial data
       base.UserVersion = base.UserVersion + 1;
      } 

      if (base.UserVersion == 1) {
        // do something else
      } 

    }

  }

Does this make sense?

The class DatabaseMapper is the following:

  public class DatabaseMapper : BsonMapper {
    public DatabaseMapper() {
         base.Entity<Post>()
           .DbRef(x => x.Tags, "tags");
    } 
  } 

Then I created an extension to inject Database class in ASP.NET Core:

    public static void AddLiteDatabase<TDatabase, TDatabaseMapper>(this IServiceCollection services, String connectionString) where TDatabase : LiteDatabase where TDatabaseMapper : BsonMapper {

      TDatabaseMapper contextMapper = (TDatabaseMapper)Activator.CreateInstance(typeof(TDatabaseMapper));

      TDatabase context = (TDatabase)Activator.CreateInstance(typeof(TDatabase), new Object[] { connectionString, contextMapper });

      services.AddScoped<TDatabase>(x => context);

    }

And on application Startup I am using:

services.AddLiteDatabase<Database, DatabaseMapper>(Configuration.GetValue<String>("ConnectionString"));

The first moment I will call the database will be on Program class as it seems that is where the data should be seeded in ASP.NET Core 3.0 Seed database in ASP.NET Core

Does this make sense?

lbnascimento commented 4 years ago

@mdmoura Regarding the documentation you linked, that's for v1, a very old version. Other than that, your solution seems good to me.