簡體   English   中英

Dapper.NET-映射多對多數據庫關系?

[英]Dapper.NET - Mapping A Many to Many Database Relationship?

我在SQL Server中有2個表,如下所示:

Table1
    int Id
    varchar(32) Name
    varchar(256) Description

Table2
    int LeftKey
    int RightKey

我在C#應用程序中有2個類,例如:

MyClass
    Name
    Description

Match
    MyClass Left
    MyClass Right

我想做的是創建一個Dapper查詢,該查詢將選擇Table2中的所有行,並聯接到Table1(* Key-> Id)並生成Match對象的列表,並相應地設置Left和Right屬性。

使用Dapper可以做到這一點嗎?

我查看了關於Stackoverflow的其他許多問題,它們似乎都與我的情況有所不同。

Dapper實際上只是一種拆分網格並快速將列分配給對象的方法。 聽起來您有兩次相同的對象-一個用於左邊,一個用於右邊。

所以...您的sql可能看起來像這樣:

select 
lk.*,
rk.*
from Table2 t2
inner join Table1 t1_left on t1_left.Id = t2.LeftKey
inner join Table1 t1_right on t1_right.Id = t2.RightKey

和您的小巧的人可能是這樣的:

connection.Query<MyClass,MyClass,Match>(sqlhere,(mc1,mc2)=>{

var match = new Match();
match.Left = mc1;
match.Right = mc2;

return match;

});

無需從SQL中的Table2返回任何內容,也無需使用Dapper自動映射它。 它實際上就像一個元組,因此我們可以在return func中創建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM