简体   繁体   中英

Repository pattern - how to combine database & in-memory entities?

I'm implementing the repository pattern, and am allowing the user of the repository to filter, project & sort the data, so that it can be done in the database level when possible. When the user adds/updates entities, the changes are made in-memory until the unit of work's Save() method is called where all the entities are persisted to the database.

This is the interface for the entity reading part in the repository:

class MyEntity
{
    public int ID {get;set;}
    public string Name {get;set;}
}

interface IMyEntityRepository
{        
    IEnumerable<MyEntity> Get<TProjection>(Expression<Func<MyEntity, TProjection>> projection, Expression<Func<MyEntity, object>> sorting);
}

The question is this: Say the user of the repository adds an entity, then tries to retrieve objects by projecting and sorting them:

using (var uow = CreateUnitOfWork())
{
    repository.Add(new MyEntity {ID = 1, Name = "Bob"});
    var result = repository.Get(projection: entity => entity.ID, sorting: entity => entity.Name);
    uow.Save();
}

So after the Add(), the added entity is still in memory, since the unit of work wasn't saved yet. Now the user queries for entities by projecting the ID but sorting by Name. Since some of the entities are in the database and some are in-memory, it seems I will need to merge the sorting in the database and the sorting of in-memory objects. How will I be able to merge the database and in-memory entities, since the data retrieved from the database by the projection (ID only) doesn't include the sorting key (Name)?

Edit : So I understand that in this case entities that were added but not yet Saved should be ignored by the repository's querying implementation. But the same question still remains for entities that were saved but are cached in the repository. How should I run the sorting on data which is partially cached?

When you are adding a new Entity that way, nothing actually happens until you run uow.Save(); .

The issue is that, you cannot use the new Entity in any operation, because you cannot be absolutely sure that it will be added in the DB (it could miss some required property or some foreign key constraint).


The solution is to first commit to unit of work and then do any operation you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM