Design bug in DbSet.Find method of Entity Framework 4.1(blogs.microsoft.co.il)

submitted by idofidof(307) 9 months, 15 days ago

This blog post shows a problem with the DbSet.Find method that creates bad queries when used in models that have entity hierarchies (inheritance).

2 comments |category: |Views: 55

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by vijaystvijayst(1311) 9 months, 15 days ago 0

Usually, we do not create complex inheritance trees while using Entity framework. The maximum depth of inheritance is usually 2. So, the case of the application crashing because of finding an entity is very remote. This is one more reason why we should avoid inheritance while using Entity framework.

Reply

posted by idofidof(307) replied to vijaystvijayst(1311), 9 months, 14 days ago 0

The matter is not only the depth of the tree, but also the number of derived types - when using queries on entity sets, the query will include all entity types, so it doesn't matter how deep your tree is but how many "nodes" you have in the tree.
One thing I see in models people build is that they use a "base entity" for all of their entity type, so if you have 50 entities which is not that far fetched, you would get a query spanning 50 tables, and that can easily throw an sql exception.

Usually people use base classes for common properties such as ID, version, etc..., but today with EF 4/4.1 you can implement it quite easily with interfaces, or even with base types that do not participate in the model (this is thanks to the T4 templates and code first options).

I don't think that the saying "avoid inheritance in EF" is correct - there are many situations where it is needed, one situation for instance is the need for polymorphism in collections, and is not always easy to implement using interfaces. What I am saying is that if inheritance is used, you must understand its meaning. Also, from my experience in EF, using a base entity for all the entity types is bad EF design, it will simply a lot of problems when running queries and when loading the model metadata into the memory, and should be avoided. Fortunatelly, EF 4/4.1 has easy ways to solve this using T4 and code first, as I mentioned before.

Reply

information Login or create an account to comment on this story