Skip to content
This repository has been archived by the owner on Oct 8, 2020. It is now read-only.

Inserts

Daniel Wertheim edited this page Nov 29, 2012 · 12 revisions

The insert methods of the unit of work is using custom datareaders over the structures, structure-indexes and structure-uniques in conjunction with (when supported by the targeted storage provider) SqlBulkCopy. Hence, we do not generate batches of inserts on our own but instead we rely on bulk-inserts which gives better performance. We support Id's that are Strings, Guids or Identities.

Insert & InsertMany

These methods are used for inserting single or many entities. Note, that you shouldn't assign values to the StructureId-property unless you have replaced the default structure builder and Id-generator.

using(var session = db.BeginSession())
{
    session.Insert(customer);
    session.InsertMany(orders);
}

InsertAs - e.g. anonymous types

From v10.0 you can now call InsertAs<T>(object item) where the item doesn't have to implement any interface or base-class defined by T. The item being passed just need to match the contract in signature, either partially or fully. You could even insert an anonymous type.

db.UseOnceTo().InsertAs<Customer>(new { CustomerNo = "124", Name = "Daniel Wertheim" });

InsertJson & InsertManyJson

These methods lets you insert raw JSON using the type defined by generics as the contract. Note! If you have an entity it's more efficient to pass that in instead of passing in the JSON data.

db.UseOnceTo().InsertJson<Customer>(myJson);
db.UseOnceTo().InsertManyJson<Customer>(myListOfJson);

Get the inserted JSON

InsertJson returns the JSON that was inserted. This is done, e.g if SisoDb is responsible for setting the StructureId, you will get the JSON with the Id-value returned for you. The same goes for InsertManyJson, but then you need to specify a callback that will be called for each batch of JSON structures being inserted.

var insertedJson = db.UseOnceTo().InsertJson<Customer>(myJson);
db.UseOnceTo().InsertManyJson<Customer>(myListOfJson, insertedJsonBatch => 
{
    foreach(var insertedJson in insertedJsonBatch)
        DoSomething(insertedJson);
});

Non generic inserts of JSON

There's also a non generic version

db.UseOnceTo().InsertJson(typeof(Customer), myJson);
db.UseOnceTo().InsertManyJson(typeof(Customer), myListOfJson);

Store as X return as Y

In this case you can have stored an entity using type X and read it back to type Y, where X doesn't event have to extend Y, only the members have to match. Read more here: Store as X return as Y

How to deal with members that you don't want to store at all

As a default behavior the serializer will try and serialize everything. So if you have e.g a MemoryStream member it will cause an exception to be thrown. The way to handle this is to define what to persist using an interface or an baseclass. Read more here.