Back to Devexpress

Hello World Console App with XPO and .NET

xpo-119377-getting-started-getting-started-with-net-core.md

latest7.7 KB
Original Source

Hello World Console App with XPO and .NET

  • Sep 14, 2022
  • 4 minutes to read

This tutorial demonstrates how to create an XPO-based .NET console application, which initializes the data layer and performs basic data operations.

Tip

The complete .NET sample project is available at https://github.com/DevExpress/XPO/tree/master/Tutorials/Console.

You can find more XPO tutorials in the Getting Started with XPO topic.

Prerequisites

Install the .NET SDK and runtime.

Create a Project

Open the system console and execute the following command to create a new C# project (you can substitute MyXpoApp with your project name):

console
dotnet new console -o MyXpoApp

To create a VB.NET project, add the -lang vb switch to the command above.

Get XPO from NuGet

Install the DevExpress.Xpo NuGet package.

console
cd MyXpoApp
dotnet add package DevExpress.Xpo

Install the Database Provider

Use the following command to install the Microsoft.Data.Sqlite package and use the local SQLite database:

console
dotnet add package Microsoft.Data.Sqlite

You can use any other .NET compatible provider XPO supports (see Database Systems Supported by XPO).

Define the Data Model

Edit the MyXpoApp/Program.cs(vb) file (or add a new code file to the project) and implement the following StatisticInfo persistent class with the Key , Info , and Date properties. The class is mapped to the StatisticInfo table with the Key , Info , and Date columns.

csharp
using DevExpress.Xpo;
// ...
public class StatisticInfo : XPLiteObject {
    public StatisticInfo(Session session)
        : base(session) {
    }
    Guid key;
    [Key(true)]
    public Guid Key {
        get { return key; }
        set { SetPropertyValue(nameof(Key), ref key, value); }
    }
    string info;
    [Size(255)]
    public string Info {
        get { return info; }
        set { SetPropertyValue(nameof(Info), ref info, value); }
    }
    DateTime date;
    public DateTime Date {
        get { return date; }
        set { SetPropertyValue(nameof(Date), ref date, value); }
    }
}
vb
Imports DevExpress.Xpo
' ...
Public Class StatisticInfo
    Inherits XPLiteObject
    Public Sub New(ByVal session As Session)
        MyBase.New(session)
    End Sub
    Private _key As Guid
    <Key(True)> _
    Public Property Key() As Guid
        Get
            Return _key
        End Get
        Set(ByVal value As Guid)
            SetPropertyValue(nameof(Key), _key, value)
        End Set
    End Property
    Private _info As String
    <Size(255)> _
    Public Property Info() As String
        Get
            Return _info
        End Get
        Set(ByVal value As String)
            SetPropertyValue(nameof(Info), _info, value)
        End Set
    End Property
    Private _date As DateTime
    Public Property Date As DateTime
        Get
            Return _date
        End Get
        Set(ByVal value As DateTime)
            SetPropertyValue(nameof([Date]), _date, value)
        End Set
    End Property
End Class

Setup the Data Layer

In the Program.cs(vb) file, change the Program.Main method. Pass the connection string to the XpoDefault.GetDataLayer method and assign the created IDataLayer object to the XpoDefault.DataLayer property.

csharp
using System.IO;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
// ...
class Program {
    static void Main(string[] args) {
        string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        string connectionString = SQLiteConnectionProvider.GetConnectionString(Path.Combine(appDataPath, "myXpoApp.db"));
        XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.DatabaseAndSchema);
    }
}
vb
Imports System.IO
Imports DevExpress.Xpo
Imports DevExpress.Xpo.DB
' ...
Friend Class Program
    Shared Sub Main(ByVal args() As String)
        Dim appDataPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
        Dim connectionString As String = SQLiteConnectionProvider.GetConnectionString(Path.Combine(appDataPath, "myXpoApp.db"))
        XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.DatabaseAndSchema)
    End Sub
End Class

Make CRUD Operations With Data

Use the UnitOfWork API to execute create, read, update, and delete (CRUD) operations. For example, you can add the following code after the data layer initialization:

csharp
using System.Linq;
using DevExpress.Xpo;
// ...
// Create data:
Console.WriteLine($"Type some text to create a new 'StatisticInfo' record.");
string userInput = Console.ReadLine();
using (UnitOfWork uow = new UnitOfWork()) {
    StatisticInfo newInfo = new StatisticInfo(uow);
    newInfo.Info = userInput;
    newInfo.Date = DateTime.Now;
    uow.CommitChanges();

}
// Read data:
Console.WriteLine($"Your text is saved. The 'StatisticInfo' table now contains the following records:");
using (UnitOfWork uow = new UnitOfWork()) {
    var query = uow.Query<StatisticInfo>()
        .OrderBy(info => info.Date)
        .Select(info => $"[{info.Date}] {info.Info}");
    foreach (var line in query) {
        Console.WriteLine(line);
    }
}
// Delete data:
using (UnitOfWork uow = new UnitOfWork()) {
    var itemsToDelete = uow.Query<StatisticInfo>().ToList();
    Console.Write($"Records count is {itemsToDelete.Count}. Do you want to delete all records (y/N)?: ");
    if (Console.ReadLine().ToLowerInvariant() == "y") {
        uow.Delete(itemsToDelete);
        uow.CommitChanges();
        Console.WriteLine($"Done.");
    }
}
vb
Imports System.Linq
Imports DevExpress.Xpo
' ...
' Create data:
Console.WriteLine($"Type some text to create a new 'StatisticInfo' record.")
Dim userInput As String = Console.ReadLine()
Using uow As New UnitOfWork()
    Dim newInfo As New StatisticInfo(uow)
    newInfo.Info = userInput
    newInfo.Date = DateTime.Now
    uow.CommitChanges()
End Using
' Read data:
Console.WriteLine($"Your text is saved. The 'StatisticInfo' table now contains the following records:")
Using uow As New UnitOfWork()
    Dim query = uow.Query(Of StatisticInfo)().OrderBy(Function(info) info.Date).Select(Function(info) $"[{info.Date}] {info.Info}")
    For Each line In query
        Console.WriteLine(line)
    Next line
End Using
' Delete data:
Using uow As New UnitOfWork()
    Dim itemsToDelete = uow.Query(Of StatisticInfo)().ToList()
    Console.Write($"Records count is {itemsToDelete.Count}. Do you want to delete all records (y/N)?: ")
    If Console.ReadLine().ToLowerInvariant() = "y" Then
        uow.Delete(itemsToDelete)
        uow.CommitChanges()
        Console.WriteLine($"Done.")
    End If
End Using

Save the changes in the Program.cs file and run the application. Use the dotnet run command in the system console to start the console application.

Note

Refer to the Deploy .NET Applications topic for information on how to deploy your application.