Skip to main content
.NET Framework 4.6.2+

How To: Connect XPO to a Database Server (ASP.NET WebForms)

  • 2 minutes to read

View Example: How to Create an ASP.NET Web Forms CRUD App

To access a database server using XPO, a data access layer needs to be created and provided with connection settings. To accomplish this in an ASP.NET application, place the construction code into the Application_Start event handler in the Global.asax module of your Web Site.

void Application_Start(object sender, EventArgs e) {
    // Code that runs on the application startup
    // Specify the connection string, which is used to open a database. 
    // It's supposed that you've already created the Comments database
    // within the App_Data folder.
    string conn = DevExpress.Xpo.DB.AccessConnectionProvider.GetConnectionString(
      Server.MapPath("~\\App_Data\\Comments.mdb"));
    DevExpress.Xpo.Metadata.XPDictionary dict =
    new DevExpress.Xpo.Metadata.ReflectionDictionary();
    // Initialize the XPO dictionary.
    dict.GetDataStoreSchema(typeof(Comment).Assembly);
    DevExpress.Xpo.DB.IDataStore store = DevExpress.Xpo.XpoDefault.GetConnectionProvider(conn,
        DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists);
    DevExpress.Xpo.XpoDefault.DataLayer = new DevExpress.Xpo.ThreadSafeDataLayer(dict, store);
    DevExpress.Xpo.XpoDefault.Session = null;
}

Note

When designing ASP.NET applications, using the ThreadSafeDataLayer object is recommended.

Handle the Web form’s Page_Init event to create a session for the XpoDataSource component. The session must be linked to the Data Layer:

using DevExpress.Xpo;

Session session1;
protected void Page_Init(object sender, EventArgs e) {
    session1 = new Session();
    XpoDataSource1.Session = session1;
}

 

When designing multi-user ASP.NET applications based on XPO, it’s recommended to create an XPO session for each request. Create a new session for each page, and dispose of it on the Page.Unload event.

protected void Page_Unload(object sender, EventArgs e) {
    xpoSession.Dispose();
}