Skip to main content
 首页 » 编程设计

c# dapper error when parameter is listint> 对象类型 >f__AnonymousType20`1[[System.Int32[] 不存在映射

2024年02月05日30zhengyun_ustc

string sqlQuery = "SELECT SellingPrice, MarkupPercent, MarkupAmount FROM ProfitMargins WHERE QuoteId in @QuoteId"; 
var profitMargin = await ctx.Database.SqlQuery<dynamic>(sqlQuery,  
    new { QuoteId = new[] { 1, 2, 3, 4, 5 } } 
//String.Join(", ", QuoteIds.ToArray()))).ToListAsync(); 

有人能看出我做错了什么吗?

No mapping exists from object type <>f__AnonymousType20`1[[System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=]] to a known managed provider native type.

我从这篇文章中得到了这个想法:SELECT * FROM X WHERE id IN (…) with Dapper ORM回答者:@LukeH

更新:

我需要将它返回到列表中。查看我的整个功能,我已经根据@JFM 发布的答案更改了代码,但现在无法添加 .ToListAsync

@JFM

public static async Task<List<dynamic>> GetProfitMargin(List<int> QuoteIds) 
{ 
    using (var conn = new SqlConnection(new MYContext().Database.Connection.ConnectionString)) 
    {    
       string sqlQuery = "SELECT SellingPrice, MarkupPercent, MarkupAmount FROM ProfitMargins WHERE QuoteId in @QuoteId"; 
        { 
            var profitMargin =  conn.Query<dynamic>(sqlQuery 
               , new { QuoteId = new[] { 1, 2, 3, 4, 5 } }).ToListAsync());                     
        } 

请您参考如下方法:

public static async Task<IEnumerable<dynamic>> GetProfitMargin(List<int> QuoteIds) 
    { 
 
        using (var conn = new SqlConnection(new MYContext().Database.Connection.ConnectionString)) 
        {    
           string sqlQuery = "SELECT SellingPrice, MarkupPercent, MarkupAmount FROM ProfitMargins WHERE QuoteId in @QuoteId"; 
            { 
                IEnumerable<dynamic> profitMargin =  await conn.QueryAsync<dynamic>(sqlQuery 
                   , new { QuoteId = new[] { 1, 2, 3, 4, 5 } });                     
            } 

如果您不将其映射到列表或数组,默认情况下它将是一个 IEnuerable。