简体   繁体   English

Dapper.NET-映射多对多数据库关系?

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

I have 2 tables in SQL Server like this: 我在SQL Server中有2个表,如下所示:

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

Table2
    int LeftKey
    int RightKey

I have 2 classes in the C# application like: 我在C#应用程序中有2个类,例如:

MyClass
    Name
    Description

Match
    MyClass Left
    MyClass Right

What I want to do is create a Dapper query which will select all rows in Table2, joining to Table1 (*Key->Id) and produce a list of Match objects with the Left and Right properties set accordingly. 我想做的是创建一个Dapper查询,该查询将选择Table2中的所有行,并联接到Table1(* Key-> Id)并生成Match对象的列表,并相应地设置Left和Right属性。

Is there a nice clean way of doing this with Dapper? 使用Dapper可以做到这一点吗?

I've looked at other many to many questions on Stackoverflow and they all seem to differ from my scenario. 我查看了关于Stackoverflow的其他许多问题,它们似乎都与我的情况有所不同。

Dapper is really just a way of splitting a grid and quickly assigning columns to an object. Dapper实际上只是一种拆分网格并快速将列分配给对象的方法。 It sounds like you just have the same object twice - one for left, one for right. 听起来您有两次相同的对象-一个用于左边,一个用于右边。

So...your sql might look like this: 所以...您的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

And your dapper might look like this: 和您的小巧的人可能是这样的:

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

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

return match;

});

No need to return anything from Table2 in your sql, nor to automatically map it with Dapper. 无需从SQL中的Table2返回任何内容,也无需使用Dapper自动映射它。 It's really just acting like a Tuple, so we can create it in the return func. 它实际上就像一个元组,因此我们可以在return func中创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM