参数为list时的c#dapper错误<int>对象类型不存在映射&lt;&gt; f__AnonymousType20`1 [[System.Int32 []

时间:2016-09-16 03:38:36

标签: c# sql dapper

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();

有人能看出我做错了吗?

  

对象类型不存在映射   &lt;&gt; f__AnonymousType20`1 [[System.Int32 [],mscorlib,Version = 4.0.0.0,   Culture = neutral,PublicKeyToken =]]到已知的托管提供者本机   类型。

我从这篇文章中得到了这个想法: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());                    
        }

3 个答案:

答案 0 :(得分:2)

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。

答案 1 :(得分:1)

使用Dapper为我查询和映射动态作品:

string sqlQuery = "SELECT SellingPrice, MarkupPercent, MarkupAmount FROM ProfitMargins WHERE QuoteId in @QuoteId";

using(var conn = new SqlConnection(myConnString)
{
    var profitMargin = conn.Query<dynamic>(sqlQuery
       , new { QuoteId = new[] { 1, 2, 3, 4, 5 } });

}

答案 2 :(得分:1)

不是100%确定问题所在,但以下是如何使用Dynamics的示例:

    [Test]
    public void TestDynamicsTest()
    {
        var query = @"select 1 as 'Foo', 2 as 'Bar' union all select 3 as 'Foo', 4 as 'Bar'";

        var result = _connection.Query<dynamic>(query);

        Assert.That(result.Count(), Is.EqualTo(2));
        Assert.True(result.Select(x => x.Foo == 1).First());
        Assert.True(result.Select(x => x.Bar == 4).Last());
    }

<强>更新

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var query = @"select 1 as 'Id', 'Foo' as 'Name' union all select 1 as 'Id', 'Bar' as 'Name'";
var result = _connection.Query<Person>(query);

foreach (var person in result)
{
    var output = string.Format("Id: {0}, Name: {1}", person.Id, person.Name);
}

有关更多示例,请查看Dapper docs