2017-06-13 77 views
1

怎樣做以下的最佳方式調用...嵌套構造從小巧玲瓏的

conn.Query<Foo>(@"SELECT 1, 2, 'ZEBRA'"); 

Foo有像這樣一個構造函數...

public Foo(Bar test, string zebra) 

..和Bar有一個構造函數像這樣:

public Bar(int one, int two) 

這不起作用,什麼是最好的方法來實現e期望的結果。

+0

'美孚(INT第一,詮釋第二,串DERP):這(新的酒吧(一,二),DERP){}' – Will

回答

2

你可以嘗試非通用查詢API(更多詳情請看這裏https://stackoverflow.com/a/8995135/229949):

conn.Query(@"SELECT 1 as one, 2 as two, 'ZEBRA' as zebra") 
    .Select(_ => new Foo(new Bar(_.one, _.two), _.zebra); 
1

不要嘗試,如果他們有這樣的構造要求,從小巧精緻的直接滋潤到你的真實模型。相反,水合到一個私人/內部類,然後實例化並返回適當的模型。

internal class FooBarQueryModel 
{ 
    public string Zebra { get; set; } 
    public int One { get; set; } 
    public int Two { get; set; } 
} 

conn.Query<FooBarQueryModel>(sql).Select(qm => new Foo(new Bar(qm.One, qm.Two), qm.Zebra)); 
+0

將這種具有對 '動態' 排液一定的優勢,也許性能? –