Question

I'm using a micro-orm (dapper) and am trying to come up with a Unit Of Work (UoW) implementation for my repositories to use. I am a little bit stumped how best to deal with parent-child (foreign key) relationships in my UoW. So for example if I have the following two entities which map directly to database tables:

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public int ClientDatabaseId { get; set; }

    public ClientDatabase ClientDb { get; set; }
}

public class ClientDatabase
{
    public int Id { get; set; }
    public string DataSource { get; set; }
    public string FailoverPartner { get; set; }
    public string InitialCatalog { get; set; }
}

Where a User has parent-child relationship with a ClientDatabase via the foreign key User.ClientDatabaseId. The Id property on both User and ClientDatabase are Identity columns. My UoW interface is defined as follows:

public interface IUnitOfWork
{
    void MarkDirty(object entity);
    void MarkNew(object entity);
    void MarkDeleted(object entity);
    void Commit();
    void Rollback();
}

At some point, within the same IUnitOfWork I want to call MarkNew() for both a ClientDatabase and a User and then Commit(). Now what I want to happen is for the ClientDatabase to be saved first (child entity) and then for the Id that was set on ClientDatabase, as a result of it's database insertion, to be set as the ClientDatabaseId foreign key property on User before it is then also inserted into the database. I just wondered whether anyone had solved this sort of problem in a nice generic fashion?

Was it helpful?

Solution

Why don't you just use your User Class as an Aggregate Root. So before you do an insert to the database for the code will check if the ClientDatabase is not null. If not null then you could check the Id property to see if its a new ClientDatabase or an existing one (to decide if you need to do an insert or an update). You could then populate the ClientDatabaseId property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top