Reputation: 287
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();
can someone see what I am doing wrong?
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.
I got this idea from this post: SELECT * FROM X WHERE id IN (…) with Dapper ORM answered by: @LukeH
UPDATE:
I need it returned into a list . see my whole function, I've changed the code according to the answer posted by @JFM, but now cannot add .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());
}
Upvotes: 1
Views: 1897
Reputation: 10219
Not 100% sure what the issue is, but below is an example of how you can work with 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());
}
Update
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);
}
For more examples, check out Dapper docs.
Upvotes: 1
Reputation: 2326
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 } });
}
If you don't map it to a list or array, by default it will be an IEnuerable.
Upvotes: 2
Reputation: 763
Using Dapper to query and map dynamic works well for me:
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 } });
}
Upvotes: 1