使用.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 步:帶參數查詢
興趣點
- 下載源代碼 - 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]第 2 步:創建項目并添加Symbiotic ORM NuGet包
在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第 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?屬性指示此映射到哪個數據庫表。還有一個DatabaseWriteTable和DatabaseReadTable允許更多的控制。
該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 providernamespace Getting_Started_With_Symbiotic_P1_CRUD_CS {// Make sure the build is set to x64class 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實例,它將用于從數據庫中讀取項目。
最后一行使用加載器從數據庫中檢索記錄作為存儲在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”方法的末尾。
前兩行我們修改了名為“newItem”的SimpleEntity實例Description。
最后一行將新數據從“newItem”實例寫入數據庫:
// ------------------------------------------------------------------------------ // Update a recordstring 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 步:帶參數查詢
第一行創建一個參數化的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包并在包文件夾中查看示例項目。
- 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
總結
以上是生活随笔為你收集整理的使用.NET Micro ORM “Symbiotic”的简单 CRUD的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中扑克牌类设计_一摞Pyth
- 下一篇: asp.net ajax控件工具集 Au