Fork me on GitHub

Initial Data Edit on GitHub


Marten supports seeding your database with initial data via the IInitialData interface. For example:


public class InitialData : IInitialData
{
    private readonly object[] _initialData;

    public InitialData(params object[] initialData)
    {
        _initialData = initialData;
    }

    public void Populate(IDocumentStore store)
    {
        using (var session = store.LightweightSession())
        {
            // Marten UPSERT will cater for existing records
            session.Store(_initialData);
            session.SaveChanges();
        }
    }
}

public static class InitialDatasets
{
    public static readonly Company[] Companies =
    {
        new Company { Name = "Netram Ltd." },
        new Company { Name = "Acme Inc." }
    };

    public static readonly User[] Users =
    {
        new User { FirstName = "Danger" , LastName = "Mouse" },
        new User { FirstName = "Speedy" , LastName = "Gonzales" }
    };
}

Add your IInitialData implementations as part of the configuration of your document store as follows:


var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // Add as many implementations of IInitialData as you need
    _.InitialData.Add(new InitialData(InitialDatasets.Companies));
    _.InitialData.Add(new InitialData(InitialDatasets.Users));
});

IInitialData.Populate(IDocumentStore store) will be executed for each configured entry as part of the initialization of your document store. They will be executed in the order they were added.