Hello World Console App with XPO and .NET(带有XPO和. NET的Hello World控制台应用程序)
This tutorial demonstrates how to create an XPO-based .NET console application, which initializes the data layer and performs basic data operations.
本教程演示如何创建基于XPO的。NET控制台应用程序,它初始化数据层并执行基本的数据操作。
Tip
The complete .NET sample project is available at https://github.com/DevExpress/XPO/tree/master/Tutorials/Console.
完整的. NET示例项目可在https://github.com/DevExpress/XPO/tree/master/Tutorials/Console获得。
You can find more XPO tutorials in the Getting Started with XPO topic.
您可以在XPO入门主题中找到更多XPO教程。
Prerequisites(先决条件)
Install the .NET SDK and runtime.
安装.NET SDK和运行时。
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):
打开系统控制台并执行以下命令来创建一个新的C#项目(您可以将MyXpoApp替换为您的项目名称):
console
dotnet new console -o MyXpoApp
To create a VB.NET project, add the -lang vb switch to the command above.
要创建VB.NET项目,请将-lang vb开关添加到上面的命令中。
Get XPO from NuGet(从NuGet获取XPO)
Install the DevExpress.Xpo NuGet package.
安装DevExpress. Xpo NuGet包。
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:
使用以下命令安装Microsoft.Data. SQLite包并使用本地SQLite数据库:
console
dotnet add package Microsoft.Data.Sqlite
You can use any other .NET compatible provider XPO supports (see Database Systems Supported by XPO).
您可以使用任何其他. NET兼容的提供程序XPO支持(请参阅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.
编辑MyXpoApp/Program. cs(vb)文件(或向项目中添加新的代码文件)并使用Key、Info和Date属性实现以下统计信息持久类。该类映射到具有Key、Info和Date列的统计信息表。
C#
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.NET
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.
在Program. cs(vb)文件中,更改Program.Main方法。将连接字符串传递给XpoDefault.GetDataLayer方法,并将创建的IDataLayer对象分配给XpoDefault.DataLayer属性。
C#
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.NET
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(使用数据进行CRUD操作)
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:
使用UnitOfWork API执行创建、读取、更新和删除(CRUD)操作。例如,您可以在数据层初始化后添加以下代码:
C#
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.NET
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.
将更改保存在Program. cs文件中并运行应用程序。使用系统控制台中的dotnet run命令启动控制台应用程序。
Note
Refer to the Deploy .NET Applications topic for information on how to deploy your application.
有关如何部署应用程序的信息,请参阅部署.NET应用程序主题。