CHAPTER 12
Whenever you start using a new technology, chances are there’s always the possibility that you will fall into one of its traps. Here I will list some of them.
This is probably obvious, but still people sometimes forget about this.
Visual Studio IntelliSense makes it very easy to write LINQ queries because it automatically shows all available properties. It may happen that some of these properties are not actually mapped. For example, they are read-only calculated columns that are computed from other properties. Accesses to these properties cannot be translated to SQL queries, so any attempt to use them in an Entity Framework query will result in an exception.
If in a loaded entity you have a null navigation property, this is probably due to one of these:
For more information, revisit the Lazy, Explicit, and Eager Loading section.
Suppose you have a validation rule in your entity that checks something on a reference property when the entity is about to be persisted. Reference properties, provided lazy loading is enabled, are automatically loaded when accessed. However, while EFCF is performing validation, this won’t happen, and references will be null. Either make sure you load all required properties before you call SaveChanges or explicitly force its loading on the validation method.
When applying the Concrete Table Inheritance pattern, you cannot use IDENTITY for generating keys. This is described in Inheritance Strategies.
When using SQL for querying your model, you cannot return entities that have complex types. This is a known limitation, and the only workaround is to get all of the entity’s values as an object array and then manually create an entity from these values.
When using the Single Table Inheritance pattern, you cannot have non-nullable properties in derived classes, because all will be created in the same table, and they won’t exist for all derived classes.
In Chapter 5, “Writing Data to the Database,” I presented a simple way to delete entities from the database without loading them first. It just happens that this won’t work if your entity has any required references. If that is the case, you need to either load the entity or attach it to the context and load that reference before deleting it.
If you try to load a navigation property in a detached entity, such as one retrieved from the ASP.NET session, the access will throw an exception because the originating context has been disposed. You will need to load all required navigation properties prior to storing them, or attach the entity to a new context. See Lazy, Explicit, and Eager Loading for more information.
This is by far the most typical problem when it comes to performance. What happens is: you issue a query, and then for each returned record, as you navigate them, you access some navigation property and another query is executed. This can be easily prevented by explicitly including the required navigation properties on the original query.