The code in this article is based on our HelloWorld sample.


First of all you should define persistent model containing one or more persistent types. Persistent type hierarchies and fields are defined using appropriate attributes.

Defining model:
[HierarchyRoot]
public class Message : Entity
{
  [Field, Key]
  public int Id { get; private set; }

  [Field(Length = 100)]
  public string Text { get; set; }
}

Domain can be configured to work with different data sources, such as in-memory database (IMDB) or one of relational databases.

Configuring domain:
<Xtensive.Storage>
  <domains>
    <domain name="memory" connectionUrl="memory://localhost/DO40-Tests" upgradeMode="Recreate" />
    <domain name="mssql" connectionUrl="mssql2005://localhost/DO40-Tests" upgradeMode="Recreate" />
    <domain name="pgsql" connectionUrl="pgsql://do4test:do4testpwd@localhost:8332/do40test?Encoding=ASCII" upgradeMode="Recreate" />
  </domains>
</Xtensive.Storage>

Before building the domain a set of persistent types or whole assembly containing them should be registered. DataObjects.Net will automatically create or upgrade database schema in accordance with the current persistent model mappings.

Building domain:
var configuration = DomainConfiguration.Load("mssql");
configuration.Types.Register(typeof(Message).Assembly);

var domain = Domain.Build(configuration);

When domain is built, we can open a session and transaction to start working with our persistent entities. DataObjects.Net transparently populates their property values from the database, as well as flushes the changes made to persistent entities back to the database.

Creating entity:
using (domain.OpenSession()) {
  using (var transactionScope = Transaction.Open()) {

    var message = new Message() {
      Text = "Hello World!"
    };

    transactionScope.Complete();
  }
}
Reading entity:
using (domain.OpenSession()) {
  using (var transactionScope = Transaction.Open()) {

    // This query will be translated to ~ SELECT ... WHERE message.Text LIKE "Hello%"
    var helloMessages = 
      from message in Query.All<Message>()
      where message.Text.StartsWith("Hello") 
      select message;

    foreach (var message in helloMessages) // Actual execution happens here
      Console.WriteLine(message.Text);

    transactionScope.Complete();
  }
}

As a result of execution of this example, the database schema will be created in SQL Server database and a single record will be inserted into MyEntity table:

Image:HelloWorld-Data.png


And the database schema will be the following:

Image:HelloWorld-Schema.png