Usage - Extended Sample

This page continues the demonstration of Phone Storage usages.
The business data are updated to:
  • work with ICollection<T>
  • provide read-only identifiers

Note: this code can be found as part of the source code in the U02_Extended.cs file.

Business Data

As in the basic sample, we use two business classes: Team and Player. Their definitions are this time a little more complicated:
  • The identifiers are read-only properties set through the constructor
  • The int identifiers have been replaced by Guid
  • The Team.Players is now a pre-initialized collection implementing ICollection<T> without a setter

/// <summary>
/// Player class - extended version.
/// </summary>
public class Player
{
    private readonly Guid identifier;

    public Player(Guid identifier)
    {
        this.identifier = identifier;
    }

    public Guid Identifier
    {
        get { return this.identifier; }
    }

    public string Name { get; set; }
}

/// <summary>
/// Team class - extended version.
/// </summary>
public class Team
{
    private readonly Guid identifier;

    private readonly ICollection<Player> players;

    public Team(Guid identifier)
    {
        this.identifier = identifier;
        this.players = new LinkedList<Player>();
    }

    public Guid Identifier
    {
        get { return this.identifier; }
    }

    public string Name { get; set; }

    public ICollection<Player> Players
    {
        get { return this.players; }
    }
}

Usage

From the previous sample, the changes are about the missing default constructor:
  • The definition is updated with an action (i => new Player(i)) that will be used when loading instance
  • The creation of initial instances used the initialized constructor

But the way to use the Phone Storage library remains the same.

// Initialize the data source
// Note the addition of the non-default constructor initialization
IDataSource ds = Engine.Instance.RegisterDataSource(new DefaultDataSourceDefinition("TeamDS")
    .AddClass<Player, Guid>(p => p.Identifier, i => new Player(i))
    .AddClass<Team, Guid>(t => t.Identifier, i => new Team(i)));

// Create business objects
Player player = new Player(Guid.NewGuid()) { Name = "Superman" };
Team team = new Team(Guid.NewGuid()) { Name = "Justice League" };
team.Players.Add(player);

// Note that all the save and retrieve calls remain the same
// Save the data
ds.Save(team);

// Load a specific instance
Player loaded = ds.Load<Player>(player.Identifier);

// Remove all the data source elements
ds.RemoveEverything();

Last edited Mar 28, 2011 at 8:16 PM by Faz, version 4

Comments

No comments yet.