Skip to main content
A newer version of this page is available. .

Connecting XPO to a Database Server (ASP.NET)

  • 2 minutes to read

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. For information on how to add the Global.asax module to the Web Site, see Tutorial 6 - A Simple Guestbook (ASP.NET).


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 by overriding the Page.Render method.


protected override void Render(HtmlTextWriter writer) {
    base.Render(writer);
    session1.Dispose();
}
See Also