I'm planning a project that will use Asp.net MVC 3 and Entity Framework 4 Code-First. When I was writing prototype I found problem. How can I map a tree in EF4? I don't think that this:
class AmazingEntity
{
public int AmazingEntityId;
public AmazaingEntity Parent;
public IList<AmazingEntity> Children;
}
Would be easy to maintain and efficient. How can I do that properly(best would be using MSSQL's native HierarchyID or some kind of other efficient tree mapping method.
Best regards and thanks in advance,
Paweł Łuczkiewcz.
Entity framework offers only the way you described because that is correct implementation of the tree structure in the object world. If you want to use any database specific features you should decide to wrap them in custom database views and map those views. The problem with this approach is that view will be read only so you will still need the mentioned entity to modify the tree.
Almost every time I need to do any query related to hieararchy traversal I use CTEs in custom view or stored procedure and use this SQL construct in EF. That is simply something that EF doesn't handle efficiently.
As you can see non of these features actually correspond with the code first approach. Pure code first doesn't allow using any database specific features (unless you add them manully in custom database initializer). Code first will use the entity you defined and create self referencing one-to-many relation. That will be all. In code-first you can't expect any database specific features or hidden database logic because that is something you can't specify in mapping.
Code-first is for situations where you want quickly define your object structure and just let EF to create DB for you. If you want to do any decisions about the database and how it should be designed you must revert to database first.
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