none
Best class model for existing database tables RRS feed

  • Question

  • Hi, I'm studing EF 4.3 and I'm trying to play around with code fist. As example I'm trying to recreate a part of our database but from the very beginning I'm having some "philosophic" or "ethic" doubts on best way to design the simple class diagram of this E-R tables diagram (I guess is a basic OO best practice problem):

    a Identity table representing a generic identity as person or company

    a 1 on 1 related Person table containing specific data for person identities (First name, last name etc)

    a 1 on 1 related Company table containing specific data for compnay identities (Firm name etc)

    This is simple to implement: A base class Identity and two child classes (Person and Company extending the Identity), and so far everything goes straight. My doubts starts when I try to add the Customer table: ok I have my Customer class, but in my database a customer can be a person or a company as well (there is a foreing key IdentityID pointing to the PK of the Identity class).  So how am I supposed to implement the Customer class? Should I put a an Identity Property (expecting EF to create a Foreign key pointing to the Identity table PK) or should extend the Identity class somehow? I'm a little bit confused about this "simple" OO design task... obviously having in mind that those classes shoud be my EF classes as well.

    Thanks

    Alessandro

    Friday, February 10, 2012 4:10 PM

Answers

  • There's no easy answer to that question, except than maybe "it depends"... :)

    My first recommendation would be to: use inheritance in the model sparingly. Yes, it is easy to go overboard and go for a full OO model with layers upon layers of inherited classes. Yes, EF supports that through three different inheritance models, but down the line it will often come back and bite you if you "overuse" it. (E.g. in terms of db-side performance, size and complexity of SQL queries etc).

    If you have a case where you clearly have something to gain in your application logic from using inheritance in your EF model, do so. If there is no obvious gain it is often better to just go for separate classes and a more simple "1:1" model with separate entity classes for different tables.

    In the example you stated above, maybe making "Customer" the base class and then "PersonCustomer" and "CompanyCustomer" inheriting from the Customer class make more sense, e.g.:


    ...if you still want a top-level abstract Identity base class you can of course keep that, but again: keep it simple unless you actually need the additional complexity.


     

       Cool tools for Linq-to-SQL and Entity Framework 4:
     huagati.com/dbmltools - Visual Studio add-in with loads of new features for the Entity Framework and Linq-to-SQL designers
     huagati.com/L2SProfiler - Runtime SQL query profiler for Linq-to-SQL and Entity Framework v4

    Monday, February 13, 2012 2:06 AM