0

I am getting an error message that says:

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

public List<Product> GetCategoryProducts(int catID)
{
    string sql = @"select p.ProductID, p.ItemName, p.ImageName
    from Product p, ProductCategory pc
    where p.ProductID = pc.ProductID
    and pc.CategoryID = @catID
        order by p.ItemName";

    List<Product> products = db.Products.SqlQuery(sql, new { catID }).ToList();
    return products;
}

I am not sure why I am getting this error

2
  • It's explained in SqlQuery method help. But why bother with SQL, this is quite simple LINQ To Entities query, you are not using the benefits of your ORM. Commented Apr 21, 2017 at 19:05
  • 2
    Please do not delete your previous question and change it to a new one. Either create a new question, or edit you question to include the additional question information (leaving the old one). By deleting the question, you are preventing anyone else from gaining benefit from your question. It's also confusing why there are answers that do not seem to address the current question. Commented Apr 21, 2017 at 19:43

1 Answer 1

2

You should do two things a) change the return type of your query, SqlQuery<Product> and b) pass the parameter catID to your query:

var products = db.Products
                 .SqlQuery<Product>(sql,new SqlParameter("catID", catID))
                 .ToList();

I am setting pc.CategoryID = @catID.

Indeed you declare a parameterized query, but you don't pass a value for your parameter. The following is just a string:

@"select p.ProductID, p.ItemName, p.ImageName
from Product p, ProductCategory pc
where p.ProductID = pc.ProductID
and pc.CategoryID = @catID 
order by p.ItemName"

You don't set there any value for the CategoryID. This is the job of SqlQuery method, that would handle this provided that you pass one.

Sign up to request clarification or add additional context in comments.

2 Comments

I added List<Product> products = db.Products.SqlQuery(sql, new { catID }).ToList(); to fix the scalar variable error
now Im getting this error: No mapping exists from object type <>f__AnonymousType6`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to a known managed provider native type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.