8

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?

Mikeb
  • 6,271
  • 3
  • 27
  • 41

1 Answers1

5

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I knew the dbSet one worked; for various reasons I don't have a dbSet where I'm interested in using the Database.SqlQuery. So it sounds like "never" is the answer. – Mikeb Sep 25 '12 at 12:55
  • Yes, there is a big difference between those two calls but I don't see a reason why you should not have `DbSet`. You have a context and you know a type so calling `dbContext.Set().SqlQuery(....)` should be possible. – Ladislav Mrnka Sep 25 '12 at 13:04
  • Was going to try that to see if it was faster or not, and remembered why I didn't do that : "The entity type (T) is not part of the model for the current context." – Mikeb Sep 25 '12 at 13:49
  • If it is not part of the model it cannot use mapping defined by attributes at all. – Ladislav Mrnka Sep 25 '12 at 14:05
  • Had wrong context, ah ha. Using dbContext.Set.SqlQuery() works, but is 5 times slower (on average) than the raw query. Guess I will live with the exceptions. – Mikeb Sep 25 '12 at 14:06