Back to Devexpress

How to: Connect to a SQL Server

xpo-4927-examples-how-to-connect-to-a-sql-server.md

latest3.0 KB
Original Source

How to: Connect to a SQL Server

  • Sep 09, 2020
  • 2 minutes to read

To make XPO use a SQL Server, you should do the following:

  • Create a SQL Server connection string.
  • Connect XPO to a database.

After the XpoDefault.ConnectionString property has been set, the default session and sessions that are manually created with default parameters will use the specified connection string. The following examples demonstrate two different ways to specify a connection string.

Supplying a SQL Server connection string

You can manually specify a SQL Server connection string. The current version of XPO determines the connection provider type from the given connection string: if it contains the “Initial Catalog” string, it is recognized as a SQL Server connection.

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

static void Main() {
    XpoDefault.Session.ConnectionString =
         @"data source=localhost\SQLEXPRESS;integrated security=true;initial catalog=Customers;";
    Application.Run(new MainForm());
}
vb
Imports DevExpress.Xpo
Imports DevExpress.Xpo.DB

Shared Sub Main()
    XpoDefault.Session.ConnectionString =
        "data source=localhost\SQLEXPRESS;integrated security=true;initial catalog=Customers;"
    Application.Run(New Form1())
End Sub

Using the GetConnectionString Function

Additionally, the GetConnectionString overloaded function of the MSSqlConnectionProvider class can be used to create the default Data Access Layer (DAL).

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

static void Main() {
  string sqlConn =
     MSSqlConnectionProvider.GetConnectionString(@"localhost\SQLEXPRESS", "Customers");
  XpoDefault.DataLayer = XpoDefault.GetDataLayer(sqlConn, AutoCreateOption.DatabaseAndSchema); 
  Application.Run(new MainForm());
}
vb
Imports DevExpress.Xpo
Imports DevExpress.Xpo.DB

Shared Sub Main()
  Dim sqlConn = MSSqlConnectionProvider.GetConnectionString("localhost\SQLEXPRESS", "Customers")
  XpoDefault.DataLayer = XpoDefault.GetDataLayer(sqlConn, AutoCreateOption.DatabaseAndSchema)
    Application.Run(New Form1())
End Sub

Note

Using the MSSqlConnectionProvider , you can also connect to SQL Azure databases. To learn more, refer to How to: Connect to SQL Azure.

See Also

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

Connect to a Data Store

How to: Connect XPO to a Database Other than Microsoft SQL or Microsoft Access