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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With