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?
Unit of Work is the concept related to the effective implementation of the repository pattern. non-generic repository pattern, generic repository pattern. Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on.
In database management, a relationship between two files. The parent file contains required data about a subject, such as employees and customers. The child is the offspring; for example, an order is the child to the customer, who is the parent.
To model a parent-child hierarchy, you create attributes, map them to the relational data source and identify which attributes represent the parent key and child key. The child key also acts as the member key. The top level member in a parent-child hierarchy is determined as the member whose parent is Null.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With