Connect to a Data Store

  • 8 minutes to read

Prerequisites

To use XPO with your database server, add a proper database provider assembly to your project's references. See the Database Systems Supported by XPO document for details.

Specify Connection Settings

Create a Data Access Layer (DAL) object using the GetDataLayer(String, AutoCreateOption) method. Pass a connection string or an existing connection object to this method as a parameter.

Use the newly created DAL for creating UnitOfWork or Session objects.

using System;
using System.Linq;
using DevExpress.Xpo;

namespace XpoConsoleApp {
    class Program {
        static void Main(string[] args) {
            // Connect to an in-memory source
            const string connectionString = @"XpoProvider=InMemoryDataStore;Data Source=.\mydatabase.xml;Read Only=false";

            var inMemoryDAL = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
            // Create and save a new data object
            using(var uow = new UnitOfWork(inMemoryDAL)) {
                var contact = new Contact(uow);
                contact.FirstName = "Alice";
                contact.LastName = "Smith";
                uow.CommitChanges();
            }
            // Read a data object
            using(var uow = new UnitOfWork(inMemoryDAL)) {
                var contact = uow.Query<Contact>().FirstOrDefault(c => c.LastName == "Smith");
                Console.WriteLine(contact.FirstName + " " + contact.LastName);
            }
        }
    }

    public class Contact : XPObject {
        public string FirstName {
            get { return fFirstName; }
            set { SetPropertyValue(nameof(FirstName), ref fFirstName, value); }
        }
        string fFirstName;

        public string LastName {
            get { return fLastName; }
            set { SetPropertyValue(nameof(LastName), ref fLastName, value); }
        }
        string fLastName;
        public Contact(Session session) : base(session) { }
    }
}

Share Connection - Default Data Access Layer

You can create a default DAL and use it an any scope of your application.

Use the XpoDefault.DataLayer static property to get or set a default data layer.

To use a default DAL, create UnitOfWork or Session objects using parameterless constructors:

using System;
using System.Linq;
using DevExpress.Xpo;

namespace XpoConsoleApp {
    class Program {
        static void Main(string[] args) {
            // Connect to an in-memory source
            const string connectionString = @"XpoProvider=InMemoryDataStore;Data Source=.\mydatabase.xml;Read Only=false";

            XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
            // Create and save a new data object
            // This Unit of Work uses a default Data Access Layer
            using(var uow = new UnitOfWork()) {
                var contact = new Contact(uow);
                contact.FirstName = "Alice";
                contact.LastName = "Smith";
                uow.CommitChanges();
            }
            // Read a data object
            // This Unit of Work uses a default Data Access Layer
            using(var uow = new UnitOfWork()) {
                var contact = uow.Query<Contact>().FirstOrDefault(c => c.LastName == "Smith");
                Console.WriteLine(contact?.FirstName + " " + contact?.LastName);
            }
        }
    }

    public class Contact : XPObject {
        // ...
        public Contact(Session session) : base(session) { }
    }
}
TIP

You can also specify a connection string in these ways:

Refer to the property descriptions for more information.

Establish Connection

A connection to a data store is established in the following cases:

If you use the XpoDefault.GetDataLayer or XpoDefault.GetConnectionProvider method, XPO keeps the connection open until the application is stopped or restarted.

If you change the database connection without restarting the application, use the following overloaded methods:

These methods have an additional out parameter that initializes a variable with an array of IDisposable objects: objectsToDisposeOnDisconnect.

using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.Xpo.Metadata;
// ...
static IDisposable[] ObjectsToDisposeOnDisconnect;
static Lazy<XPDictionary> SharedDictionary = new Lazy<XPDictionary>(CreateSharedDictionary);

static void ChangeConnection(string connectionString) {
    if(ObjectsToDisposeOnDisconnect != null) {
        foreach(IDisposable toDispose in ObjectsToDisposeOnDisconnect)
            toDispose.Dispose();
    }
    XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, SharedDictionary.Value, AutoCreateOption.SchemaAlreadyExists, out ObjectsToDisposeOnDisconnect);
}

static XPDictionary CreateSharedDictionary() {
    XPDictionary result = new ReflectionDictionary();
    result.GetDataStoreSchema(typeof(Contact).Assembly);
    return result;
}

If you want to have full control over the connection state (open/closed), create an IDbConnection object manually and pass it to a Data Store Provider via a constructor.

using DevExpress.Xpo;
using DevExpress.Xpo.DB;

using Microsoft.Data.SqlClient;
// ...
SqlConnection Connection;

void Connect(string connectionString) {
    Connection = new SqlConnection(connectionString);
    MSSqlConnectionProvider dataStoreProvider = new MSSqlConnectionProvider(Connection, AutoCreateOption.SchemaAlreadyExists);
    XpoDefault.DataLayer = new SimpleDataLayer(dataStoreProvider);
}

If you use the ConnectionString or Connection property, the connection is alive while a session is active: until the Session.Disconnect method is explicitly called. This method is implicitly called when a Session object is disposed of.

How It Works

Data Store Provider

A data store provider is an IDataStore implementation, which provides a connection to individual data stores (Microsoft SQL Server, MySQL databases, etc.)

See also: DataStoreBase.

Data Access Layer

A data access layer (DAL) (an IDataLayer implementation) enables a unified access to data stores (loading data from a data store, updating its data and schema) via object access layers.

Share DAL for Performance Optimization

Each Session or UnitOfWork object creates a new DAL when a connection to a data store is about to be established. You can force a Session or UnitOfWork to use an existing DAL. In this case, specific initialization steps are omitted and the connection is established faster.

To make a session use a specific DAL do one of the following.

See also: IDataLayerAsync.

Object Access Layer

An object access layer (OAL) is a mediator between a Session or UnitOfWork and a data access layer. An OAL translates object queries and storage schema updates to corresponding statements, and passes them to a data access layer for execution.

XPO has the following object access layer implementations.

See also: IObjectLayerAsync.

Concepts

NOTE

You can try the functionality described here in the Connecting to a Data Store section of the XPO Tutorials demo (C:\Users\Public\Documents\DevExpress Demos 20.1\Components\WinForms\Bin\XpoTutorials.exe).

Task-Based Help