Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should you handle parent and child entities in the repository pattern?

I'm working on making a image site and I'm wondering how I should structure the Create/Update methods in my Linq to Sql repository?

I have a Photo entity that is structured like:

public class Image
{
    public int ID { get; set; }
    public int OwnerId { get; set; }
    public string Url { get; set; }
    public IEnumerable<Tag> Tags { get; set; }
}

I have the following tables: Images, Tags, ImageTag

Now, I'm wondering when I call my CreateImage method in my ImageRepository, should I also be creating the Tags in the Tags table and the making the mappings in the ImageTag table?

Likewise, when I call UpdateImage, should I be checking if the tags have changed, and if they have then deleting entries in the ImageTag table and adding in different ones (as well as possibly adding new Tags to the tags table)?

Or should both of these use cases happen in a separate repository call?

Basically, how is this parent/child, one-to-many relationship handled typically in a typical linq to sql repository?

like image 246
Viktor Avatar asked Nov 05 '22 16:11

Viktor


1 Answers

I would say it is not the responsibility of the repository to understand the relationships between the entities in your model. After all, if you were to change the way you persist your data (to a no-sql solution for example, or even if you just change your db schema), your entities and your model shouldn't change.

So your best bet is to have separate repository calls, and wrap the calls inside a unit of work. (A Unit of Work is basically an abstracted out transaction).

Your unit of work and the various calls to the repository would be a layer of abstraction above the repository. I don't know the rest of your model, so that could be different things. It could be a method on the Image object. You could have a Mediator. Or, if you are approaching this from a DDD perspective, a Domain Service.

Cheers.

like image 193
Nik Pinski Avatar answered Nov 14 '22 22:11

Nik Pinski