65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET Micro ORM "Symbiotic" 实现简单的 CRUD 操作

starIconstarIconstarIconstarIconstarIcon

5.00/5 (9投票s)

2019 年 1 月 18 日

CPOL

4分钟阅读

viewsIcon

30274

downloadIcon

285

本文演示了使用 .NET Symbiotic ORM 执行数据库的创建、读取、更新、删除操作。

引言

本文将教您如何使用 .NET Symbiotic Micro ORM 将对象的數據讀寫到數據庫。Symbiotic 是一款免费的 .NET ORM,支持以下数据库供应商:SQL Server、SQL Azure、My SQL、Sqlite、Oracle、PostgreSql、Firebird、DB2/LUW。

本文将重点介绍 SQL Server 数据库。本文假设您具备 C# 和 SQL Server 的基础知识。

背景

您需要一个 SQL Server 数据库,可以是本地数据库文件、服务器数据库或 Azure SQL 数据库。

请确保您的项目生成为 x64。请参阅菜单:“生成 \ 配置管理器”。

步骤 1:创建 SimpleEntities 表

运行以下 SQL 脚本来创建本文将使用的表。

CREATE TABLE [dbo].[SimpleEntities](
    [EntityId] [int] IDENTITY(1,1) NOT NULL,
    [Description] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_SimpleEntities] PRIMARY KEY CLUSTERED
(
    [EntityId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
       ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

步骤 2:创建项目并添加 Symbiotic ORM NuGet 包

在 Visual Studio 中为 .NET 4.6.1 或更高版本创建一个新的 C# 控制台项目。

然后添加 Nuget 包“Symbiotic_Micro_ORM_Net_Standard_x64”。您可以使用主菜单:“项目 \ 管理 Nuget 包…

您可能需要刷新“解决方案资源管理器”中的项目以更新引用。

步骤 3:为 Symbiotic ORM 添加 using

将以下 using 行添加到“Program”类的顶部。

    using FrozenElephant.Symbiotic;
    using FrozenElephant.Symbiotic.DataProviderSqlServer; // Using the Sql Server data provider

步骤 4:创建 SimpleEntity 类

向项目中添加一个名为“SimpleEntity”的新类。

此类将用于表示您在步骤 1 中创建的表。

替换或修改“SimpleEntity”类的代码以匹配下面的代码

    [Serializable, DatabaseTable("SimpleEntities"), 
    DebuggerDisplay("SimpleEntity: EntityId= {EntityId},  Description= {Description}")]
    public class SimpleEntity
    {
        [DatabaseColumn("EntityId", IsPrimaryKey = true, IsIdentityColumn = true)]
        public int EntityId { get; set; }

        [DatabaseColumn("Description")]
        public string Description { get; set; }
    }

DatabaseTable 属性指示该对象映射到哪个数据库表。还有 DatabaseWriteTableDatabaseReadTable 以允许更多控制。

DatabaseColumn 属性指示 SQL 结果中的数据库列/字段名称,用于映射到对象的属性。如果存在 DatabaseColumn,ORM 会期望找到结果,否则会发生错误。

步骤 5:为 Symbiotic ORM 添加 using

将以下 using 行添加到“Program”类的顶部

    using FrozenElephant.Symbiotic;
    using FrozenElephant.Symbiotic.DataProviderSqlServer; // Using the Sql Server data provider

步骤 6:初始化 Factory 类

在“Main”方法的开头添加以下代码行。

这些行初始化 Factory 类并设置数据库连接字符串。

您需要修改连接字符串以匹配您的数据库、服务器和用户/密码。

// Initialize the factory and set the connection string
_DBTypesFactory = new DatabaseTypesFactorySqlServer(); // using sql server provider
_DBTypesFactory.ConnectionString = "Data Source=yourServer;
Initial Catalog=yourDatabase;User ID=ZZZZZZZ;Password=XXXXXX;
Connect Timeout=35;Encrypt=False;TrustServerCertificate=True;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False;MultipleActiveResultSets=true;Enlist=false";

您的“Program”类现在应该看起来像下面的代码

using System;
using System.Collections.Generic;
using System.Data;

using FrozenElephant.Symbiotic;
using FrozenElephant.Symbiotic.DataProviderSqlServer; // Using the Sql Server data provider

namespace Getting_Started_With_Symbiotic_P1_CRUD_CS
{
    // Make sure the build is set to x64
    class Program
    {
        // the factory is where all Symbiotic ORM objects are created, 
        // this allows the developer to override creation as needed.
        private static IDatabaseTypesFactory _DBTypesFactory;

        static void Main(string[] args)
        {
            // Initialize the factory and set the connection string
            _DBTypesFactory = new DatabaseTypesFactorySqlServer(); // using SQL Server provider
            _DBTypesFactory.ConnectionString = "Data Source=yourServer;
            Initial Catalog=yourDatabase;User ID=ZZZZZZZ;Password=XXXXXX;
            Connect Timeout=35;Encrypt=False;TrustServerCertificate=True;
            ApplicationIntent=ReadWrite;MultiSubnetFailover=False;
            MultipleActiveResultSets=true;Enlist=false";
        }
    }
}

步骤 7:创建一条记录

将以下行添加到“Main”方法的末尾。

前两行创建“SimpleEntity”类的一个新实例并填充描述。

第三行创建了一个名为“writer”的 IObjectWriter 实例,它将用于将项目写入数据库。

最后一行将“SimpleEntity”中包含的数据写入数据库。

// ---------------------------------------------------------------------------
// create a record
SimpleEntity newItem = new SimpleEntity();
newItem.Description = "Description " + DateTime.Now.ToString();
    
// create the writer object, this class is used for all writes
IObjectWriter writer = _DBTypesFactory.CreateObjectWriter();
            
// call create on the writer passing in the instance to save to the database
writer.Create(newItem); // note: the primary key property "EntityId" will be populated after the write

步骤 8:读取一条记录

将以下行添加到“Main”方法的末尾。

第一行创建了一个名为“loader”的 IObjectLoader 实例,它将用于从数据库读取项目。

最后一行使用加载器将记录从数据库检索为一个填充的“SimpleEntity”实例,并存储在 loadedItem 变量中。

// ------------------------------------------------------------------------------
// Read a single record

// create the loader object, this class is used for all reads
IObjectLoader loader = _DBTypesFactory.CreateObjectLoader();

SimpleEntity loadedItem = loader.ObtainItem<SimpleEntity>(newItem.EntityId);

步骤 9:更新一条记录

将以下行添加到“Main”方法的末尾。

前两行我们修改了名为“newItem”的 SimpleEntity 实例的 Description

最后一行将“newItem”实例中的新数据写入数据库

// ------------------------------------------------------------------------------
// Update a record

string newDesc = "Updated " + DateTime.Now.ToString();
newItem.Description = newDesc;
writer.Update(newItem);

步骤 10:插入或更新一条记录

将以下行添加到“Main”方法的末尾。

前两行我们修改了名为“newItem”的 SimpleEntity 实例的 Description

最后一行将插入“newItem”实例记录(如果记录不存在),否则将更新它。

// ------------------------------------------------------------------------------
// InsertUpdate a record

// InsertUpdate will create or update, the ORM checks if it exists, 
// if so then updates the record otherwise it creates it.
string newDesc2 = "Updated " + DateTime.Now.ToString();
newItem.Description = newDesc2;
writer.InsertUpdate(newItem);

步骤 11:删除一条记录

将以下行添加到“Main”方法的末尾。

此行从数据库中删除“newItem”实例

// ------------------------------------------------------------------------------
// Delete a record
writer.Delete(newItem);

步骤 12:查询多条记录

第一行是标准的 SQL,用于返回“SimpleEntities”表中的所有记录。

第二行创建了一个运行查询所需的 ISqlQuery 实例。

第三行运行查询并返回 SimpleEntity 项的集合。

请记住,如果您没有任何记录,集合将为空。

// -----------------------------------------------------------------------------
// Query multiple records
string sql = "Select * from simpleEntities";
ISqlQuery query = _DBTypesFactory.CreateSqlQuery(sql, "My simple sql");

IList<simpleentity> items = loader.ObtainItems<simpleentity>(query);

步骤 13:带参数的查询

第一行创建一个带有名为“max”的参数的参数化 SQL 语句。

第二行创建了一个运行查询所需的 ISqlQuery 实例。

第三行创建了一个参数,并将该参数及其值“3”加载到查询中。

第四行运行查询并返回 SimpleEntity 项的集合。

请记住,如果没有记录匹配查询的 where 子句,则集合将为空。

// -----------------------------------------------------------------------------
// Query with parameters
string sql2 = "Select * from simpleEntities where Entityid > @max";
ISqlQuery query2 = _DBTypesFactory.CreateSqlQuery(sql2, "My simple sql");
query2.CreateAndAddParameter(_DBTypesFactory, DbType.Int32, "max", 3);
            
IList<SimpleEntity> items2 = loader.ObtainItems<SimpleEntity>(query2);

关注点

本文仅触及了“Symbiotic”ORM 功能的皮毛。有关更高级的功能细节和示例,请下载 nuget 包并在包文件夹中查找示例项目。

还有一个配套应用程序,可以为现有数据库创建 poco 类

历史

  • 2019 年 1 月 21 日:初始版本
© . All rights reserved.