Search code examples
c#entity-frameworkoopsolid-principles

Proper way to model a child class with properties from its relationship


I have a Lawsuit class that has an Employer list. There's a requirement that one of the employers on the list must be set as the main employer. I thought of two ways to meet this business rule.

Solution 1

This is my current implementation, I have a MainEmployer and I store the same entity on this property and on the Employers list:

public class Lawsuit()
{
    public int Id { get; set; }

    public virtual Employer MainEmployer { get; set; }
    public virtual ICollection<Employer> Employers { get; set; }
}

Solution 2

I could also create an in-between class EmployerLawsuit with a bool property called Main:

public class LawsuitEmployer()
{
    public int Id { get; set; }
    public bool Main { get; set; }

    public virtual Employer Employer { get; set; }
    public virtual Lawsuit Lawsuit { get; set; }
}

public class Lawsuit()
{
    public int Id { get; set; }

    public virtual ICollection<EmployerLawsuit> Employers { get; set; }
}

Which of these two approaches is better considering the performance of the resulting database (I'm using Entity Framework) and the principles of SOLID? Or is there a better way to model these entities?


Solution

  • I'd stick with #1 approach. It's just an one-to-many/many-to-one association between a Lawsuit and an Employer. That is, the so-called association will be retrieved as part of a SQL join when retrieving a Lawsuit persistent object, and in addition, you won't need to query all employers to check which one is the main employer.

    In terms of object-oriented programming #1 sounds better and the domain will perform better when mapped to either a relational or NoSQL database using an O/RM.

    About #2

    Actually #2 sounds more like designing the domain the relational way. It would be a domain designed to be queryable, while object-oriented programming produces hierarchical models, and that's the main reason to express your domain with associations rather than using flags or identifiers to define the relationships of your domain entities.

    You don't need a flag to mark an entity as the main employer and implement a hierarchy for this. Keep it simple: set the whole MainEmployer association and go!