JTunney
JTunney

Reputation: 904

Returning an anonymous type when using context.Object.SqlQuery

Lets say I want to select the first product returned in a category, but I need to do it passing a sql string directly. Notice how I am specifying context.Products.SqlQuery. I thought this would work even if I don't select all of the product fields in my query. Do I really have to select an anonymous type and then convert it to a product?

The error I am getting is: The data reader is incompatible with the specified 'AppModel.Product'. A member of the type, 'InsertDate', does not have a corresponding column in the data reader with the same name.

Below is my code:

StringBuilder sql = new StringBuilder();

sql.AppendLine("SELECT Id, ProductName ");
sql.AppendLine("FROM Product ");
sql.AppendLine("WHERE CategoryId=@CategoryId ");
var retval = context.Products.SqlQuery(sql.ToString(),
         new SqlParameter("@CategoryId", categoryId)).FirstOrDefault();

return retval;

Upvotes: 0

Views: 169

Answers (1)

Tim
Tim

Reputation: 15227

Entity Framework can't construct the whole Product object from the results of your SQL statement because you're only returning those two fields. It should work if you did:

sql.AppendLine("Select * ");
sql.AppendLine("FROM Product ");
...

or if you specified all of the fields manually.

Upvotes: 2

Related Questions