Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting Entity Framework raw query to respect attributes

I'm using EF4, code first. As such, my model classes have a mix of public properties, some virtual properties (for lazy loaded data from other tables) and some properties that are affixed with [NotMapped] attributes so that they are skipped by EF.

Sometimes I like to make use of the raw query : c.Database.SqlQuery<T>("select ...") to use EF as a row mapper.

I noticed in Intellitrace that these queries were generating a lot of thrown and caught exceptions for "IndexOutOfRange". After some looking, the exceptions are all for the virtual and [NotMapped] properties on the model object. I don't want to have to construct a new data model class or parent class with just the table properties in it; is there some configuration step I've missed to tell the row mapper in the raw query runner to pay attention to the same annotations that the rest of EF uses? Maybe they fixed this in EF5?

like image 482
Mikeb Avatar asked Sep 24 '12 21:09

Mikeb


People also ask

How do I run a raw SQL query using DbContext?

From the DbContext 's database object, create the Db command. Then, assign all the required parameters to the command object like the SQL, Command Type, SQL parameters, use existing DB transition, and optional command timeout to the command. Finally, calling ExecuteNonQuery() to execute the raw SQL query.

Which method is used to retrieve data using SQL query statements in EF?

The DbSet. FromSqlRaw method ( DbSet. FromSql prior to Entity Framework Core 3.0) enables you to pass in a SQL command to be executed against the database to return instances of the type represented by the DbSet : public class Book.


1 Answers

If you execute dbContext.Database.SqlQuery EF will never use mapping. It will use just simple match of property names and columns in result set. Try to use dbSet.SqlQuery instead. It should reflect mapping because it can load data as attached entities.

like image 135
Ladislav Mrnka Avatar answered Oct 21 '22 14:10

Ladislav Mrnka