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

Store as x return as y

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

Since objects are serialized and deserialized using Json as the format there is no schema. This means that when you insert an entity of type X you can use the methods below to have it returned as another type with matching members (all or any):

  • GetByIdAs<TContract, TOut>
  • Query.ToListOf
  • NamedQueryAs<TContract, TOut>

TContract

This is used as the template for building the database schema and to extract values from the entity being passed in. These values are stored in the Indexes table used for querying. The entity being passed in is then serialized to Json and stored in the Structure table. Note! If TContract is e.g Person and you store a SalesPerson, it will be indexed as Person but serialized as SalesPerson.

TContract, Must have an Id property

The typedefinition used as TContract must have the StructureId member (named StructureId, [TypeName]Id or Id) otherwise an exception will be thrown. This means that when you query an entity using the above functions you can specify TOut to be something that has all or a set of all the members of the TContract.

Example - GetByIdAs

In this case you can have stored an entity using WriteSession.Insert<T>() where T is an interface or baseclass and then you wan't to retrieve it as something that extends the interface or baseclass or even something that doesn't extend it.

public interface IPhoto
{
    Guid Id { get; set; }
    string Name { get; }
    string Path { get; }
    int Votes { get; }
    string[] Tags { get; }
}

public class Photo : IPhoto
{
    public Guid Id { get; set; }
    public string Name { get; private set; }
    public string Path { get; private set; }
    public int Votes { get; private set; }
    public string[] Slugs { get; private set; }
}

public class PhotoInfo
{
    public string Name { get; private set; }
    public string Path { get; private set; }
}
var photo = new Photo();

using (var session = Db.BeginSession())
{
    session.Insert<IPhoto>(photo);

    var asPhoto = session.GetByIdAs<IPhoto, Photo>(photo.Id);
    var asPhotoInfo = session.GetByIdAs<IPhoto, PhotoInfo>(photo.Id);
    ...
}
Clone this wiki locally