2016-02-07 40 views
0

是否有可能創建下面的書面短小精悍查詢,作爲IEnumerable<dynamic>作爲我沒有產品&供應商POCO。在短小精悍連接查詢中使用動態對象列表

IEnumerable<Product> products = sqlConnection 
        .Query<Product, Supplier, Product>(
         @"select Products.*, Suppliers.* 
          from Products join Suppliers 
           on Products.SupplierId = Suppliers.Id 
           and suppliers.Id = 2", 
         (a, s) => 
          { 
           a.Supplier = s; 
           return a; 
          }); 

如果我的sql查詢是一件下面,我短小精悍的查詢將如何與IEnumerable<dynamic>

select Products.ProductId,Products.ProductName,Products.ProductCategory, ProductPrice.Amount,ProductPrice.Currency 
           from Products join ProductPrice 
            on Products.ProductId = ProductPrice.ProductId 

所有幫助的返回類型是真誠的讚賞。

感謝

回答

0

是的,你可以映射你的查詢的動態對象的列表的結果(文檔here)。

const string sql = @"select Products.ProductId, Products.ProductName, Products.ProductCategory, ProductPrice.Amount, ProductPrice.Currency 
         from Products join ProductPrice 
         on Products.ProductId = ProductPrice.ProductId"; 

    IEnumerable<dynamic> products = sqlConnection.Query(sql); 

在你正在做的multi mapping其中每個錶行映射到2個物體而不是一(ProductSupplier),然後由參考鏈接被返回產品之前的第一個例子。我不認爲你可以用動態對象來做到這一點,因爲Dapper無法知道如何劃分它們之間的列。您可以通過測試來確認此項,用<dynamic, dynamic, dynamic>替代通用參數<Product, Supplier, Product>

跳過多重映射只會意味着dynamic對象返回將包含ProductSupplier屬性,這可能不會對您造成問題。

相關問題