目录
介绍
背景
第 1 步:创建SimpleEntities表
第 2 步:创建项目并添加Symbiotic ORM NuGet包
第 3 步:为Symbiotic ORM添加使用
第 4 步:创建SimpleEntity类
第 5 步:为Symbiotic ORM添加使用
第 6 步:初始化工厂类
第 7 步:创建记录
第 8 步:读取记录
第 9 步:更新记录
第 10 步:插入或更新记录
第 11 步:删除记录
第 12 步:查询多条记录
第 13 步:带参数查询
兴趣点
- 下载源代码 - 1.8 MB
本文将教您如何使用.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]
在Visual Studio中为.NET 4.6.1或更高版本创建一个新的C#控制台项目。
然后添加Nuget包“Symbiotic_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
将一个名为“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 属性指示此映射到哪个数据库表。还有一个DatabaseWriteTable和DatabaseReadTable允许更多的控制。
该DatabaseColumn 属性指示SQL结果中的数据库列/字段名称以映射到对象的属性。如果DatabaseColumn存在,则ORM期望找到结果,如果不存在,则会发生错误。
第 5 步:为Symbiotic ORM添加使用将以下using行添加到"Program"类的顶部:
using FrozenElephant.Symbiotic;
using FrozenElephant.Symbiotic.DataProviderSqlServer; // Using the Sql Server data provider
在"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";
}
}
}
将以下行添加到“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
将以下行添加到“Main”方法的末尾。
第一行创建了一个名为“loader”的IObjectLoader实例,它将用于从数据库中读取项目。
最后一行使用加载器从数据库中检索记录作为存储在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(newItem.EntityId);
将以下行添加到“Main”方法的末尾。
前两行我们修改了名为“newItem”的SimpleEntity实例Description。
最后一行将新数据从“newItem”实例写入数据库:
// ------------------------------------------------------------------------------
// Update a record
string newDesc = "Updated " + DateTime.Now.ToString();
newItem.Description = newDesc;
writer.Update(newItem);
将以下行添加到“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);
将以下行添加到“Main”方法的末尾。
此行从数据库中删除“newItem”实例:
// ------------------------------------------------------------------------------
// Delete a record
writer.Delete(newItem);
第一行是标准SQL,用于返回"SimpleEntities"表中的所有记录。
第二行创建一个运行查询所需的ISqlQuery实例。
第三行运行查询并返回SimpleEntity项集合。
请记住,如果您没有记录,则该集合将为空。
// -----------------------------------------------------------------------------
// Query multiple records
string sql = "Select * from simpleEntities";
ISqlQuery query = _DBTypesFactory.CreateSqlQuery(sql, "My simple sql");
IList items = loader.ObtainItems(query);
第一行创建一个参数化的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 items2 = loader.ObtainItems(query2);
这篇文章几乎没有触及“Symbiotic”ORM功能的表面。有关更多高级功能的详细信息和示例,请下载nuget包并在包文件夹中查看示例项目。
- NuGet Gallery | Symbiotic_Micro_ORM_Net_Standard_x64 3.0.0
还有一个配套应用程序将为现有数据库创建poco类:
- Microsoft Apps
https://www.codeproject.com/Articles/1274712/Simple-CRUD-with-the-NET-Micro-ORM-Symbiotic