有没有办法做这样的事情?假设我有两节课:
public class Class_A
{
public string Name {get;}
public string Age {get;}
public int Key {get;}
}
public class Class_B
{
public string Doors {get;}
public string Windows {get;}
public int Key {get;}
}
然后是这样的组合类:
public class Class_C
{
public Class_A CA {get;}
public Class_B CB {get;}
}
现在让我们说我正在说
_connection.Query<Class_C>("A SQL that returns results from JOIN of Clas_A and Class_B")
那么它就能够以某种方式知道将哪个字段映射到哪个字段。 因为否则我必须再次将这两个类的字段复制粘贴到 Class_C 中,如下所示:
public class Class_C
{
public string Name {get;}
public string Age {get;}
public string Doors {get;}
public string Windows {get;}
}
未经测试,但我认为你可以这样写:
string cmd = @"select a.Key, a.Name, a.Age,
b.Key, b.Doors, b.Windows
from Class_A a INNER JOIN Class_B b on a.Key = b.Key";
var listOfC = connection.Query<Class_A, Class_B, Class_C>(cmd, (a,b) =>
{
Class_C c = new Class_C();
c.CA = a;
c.CB = b;
return c;
}, splitOn:"Key");
如果您只想使用具有 A 和 B 的所有属性的 Class_C,那就很简单
string cmd = @"select a.Key, a.Name, a.Age,
b.Doors, b.Windows
from Class_A a INNER JOIN Class_B b on a.Key = b.Key";
var listOfC = connection.Query<Class_C>(cmd);
Dapper 只会将字段映射到 Class_C 的属性