Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Domain Model + repository: Where to put code that loads an entity

I have a model class which is loaded from a "GetById" method in my repository class. I now need to add additional properties to this entity, which aren't saved in the database, but are calculated by a service class. Something like:

public class MyEntity
{
    public int ThingId { get; set; };
    public string ThingName { get; set; }

    // Set from the service
    public int WooFactor { get; set; }
}

public class WooFactorGenerator
{
    public int CalculateWooFactor(MyEntity thing); // Hits other services and repo's to eventually determine the woo factor.
}

// Code to get a "MyEntity":

var myEntity = repo.GetById(1);
var gen = new WooFactorGenerator();
myEntity.WooFactor = gen.CalculateWooFactor(myEntity);

So in order to load/saturate a MyEntity object, I need to load from the db, and then call the generator to determine the "woo factor" (ahem). Where should this code go from an architectural viewpoint? Current thoughts:

1) In the repository: I feel like I'm handing too much responsibility to the repo if I add it here.

2) In the "MyEntity" class. Add the code in here that perhaps lazy-loads the WooFactor when it is accessed. This would add a lot of dependencies to MyEntity.

3) A separate service class - seems overkill and un-necessary.

like image 496
Matt Roberts Avatar asked May 03 '11 13:05

Matt Roberts


2 Answers

  • If WooFactor is purely dependent on MyEntity properties then it must be done inside MyEntity
  • If it requires external info (such as configuration, rules, etc) then it needs to be a separate service outside Repository. I would create a WooEntity here with this additional property.

In any case, it should never be in the Repository.

like image 108
Aliostad Avatar answered Sep 22 '22 07:09

Aliostad


Google CQRS. What you need to do is to separate the read and write concerns. If the calculation is needed by something else other than the entity, you have your answer in plain sight.

like image 38
Adam Dymitruk Avatar answered Sep 21 '22 07:09

Adam Dymitruk