【NPoco】一對多查詢操作
阿新 • • 發佈:2018-11-04
ORM庫:NPoco
GitHub:https://github.com/schotime/NPoco
我Fork了一份在gitee:https://gitee.com/sesametech-group/NPoco
今天介紹實現一個一對多的關聯查詢功能
首先新增資料庫表格:
CREATE TABLE `one` ( `OneId` INT(11) NOT NULL AUTO_INCREMENT, `Name` VARCHAR(50) NULL DEFAULT NULL, PRIMARY KEY (`OneId`) ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=4 ;
CREATE TABLE `many` (
`ManyId` INT(11) NOT NULL AUTO_INCREMENT,
`OneId` INT(11) NULL DEFAULT NULL,
`Value` INT(11) NULL DEFAULT NULL,
`Currency` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`ManyId`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;
建立實體類:
[TableName("One"),PrimaryKey("OneId")] public class One { public int OneId { get; set; } public string Name { get; set; } [ResultColumn,ComplexMapping] public NestedClass Nested { get; set; } [Reference(ReferenceType.Many,ColumnName = "OneId",ReferenceMemberName = "OneId")] public ListMany Items { get; set; } } public class NestedClass { public string Name { get; set; } } public class ListMany : List<Many> { } [TableName("Many"),PrimaryKey("ManyId")] public class Many { public int ManyId { get; set; } [Reference(ReferenceType.OneToOne,ColumnName = "OneId",ReferenceMemberName = "OneId")] public One One { get; set; } public int OneId { get; set; } public int Value { get; set; } public string Currency { get; set; } }
在 One 類中新添加了一個屬性:Nested,型別為CLASS,並在類中添加了型別為ListMany的Items屬性。
通過如下的語句實現一對多查詢:
第一行程式碼:實現了一對多查詢,但是屬性Nested沒有值
第二行程式碼:實現了一對多查詢,並在sql中添加了地段:nested__name,並把常量“MyName“賦給了nested__name。
var ones = database.FetchOneToMany<One>(x => x.Items, @"select o.*, m.* from ONE o left join many m on o.oneid = m.oneid"); var x2= database.FetchOneToMany<One>(x => x.Items, "select o.*, 'MyName' nested__name, null npoco_items, m.* from ONE o left join many m on o.oneid = m.oneid");
一、 第一個查詢結果
1.1 資料庫根據語句查詢結果
1.2 程式通過監視器可以看到其中的結果如下圖所示:
二、第二個查詢結果
2.1 資料庫根據語句查詢結果
2.2 通過監視器可以看到其中的結果如下圖所示:
根據一和二可以看到,查詢到了我們想要的結果