使用.NET Micro ORM “Symbiotic”的简单 CRUD

目录

介绍

背景

第 1 步:创建SimpleEntities表

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

第 3 步:为Symbiotic ORM添加使用

第 4 步:创建SimpleEntity类

第 5 步:为Symbiotic ORM添加使用

第 6 步:初始化工厂类

第 7 步:创建记录

第 8 步:读取记录

第 9 步:更新记录

第 10 步:插入或更新记录

第 11 步:删除记录

第 12 步:查询多条记录

第 13 步:带参数查询

兴趣点


介绍

本文将教您如何使用.NET Symbiotic Micro ORM读取对象数据并将其写入数据库。Symbiotic是一个免费的.NET ORM,它支持以下数据库供应商:SQL ServerSQL AzureMy SQLSqliteOraclePostgreSqlFirebirdDB2/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#控制台项目。

然后添加NugetSymbiotic_Micro_ORM_Net_Standard_x64。您可以使用主菜单:Project \ Manage Nuget Packages...

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

3 步:为Symbiotic ORM添加使用

将以下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行添加到"Program"类的顶部:

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

6 步:初始化工厂类

"Main"方法的开头添加以下代码行。

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

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

// 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类的新实例并填充描述。

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

最后一行将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方法的末尾。

第一行创建了一个名为loaderIObjectLoader实例,它将用于从数据库中读取项目。

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

// ------------------------------------------------------------------------------
// 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方法的末尾。

前两行我们修改了名为newItemSimpleEntity实例Description

最后一行将新数据从newItem实例写入数据库:

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

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

10 步:插入或更新记录

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

前两行我们修改了名为newItemSimpleEntity实例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 步:带参数查询

第一行创建一个参数化的SQL语句,其参数名为max

第二行创建一个运行查询所需的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类:

https://www.codeproject.com/Articles/1274712/Simple-CRUD-with-the-NET-Micro-ORM-Symbiotic

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值