Repository pattern and mapping between domain models and Entity Framework

后端 未结 6 1209
后悔当初
后悔当初 2020-12-04 07:15

My repositories deal with and provide persistence for a rich domain model. I do not want to expose the anemic, Entity Framework data entity to my business layers, so I need

6条回答
  •  醉话见心
    2020-12-04 07:34

    I like using custom-built Extension methods to do the mapping between Entity and Domain objects.

    • You can easily call extension methods for other entities when they are within a containing entity.
    • You can easily deal with collections by creating IEnumerable<> extensions.

    A simple example:

    public static class LevelTypeItemMapping
    {
        public static LevelTypeModel ToModel(this LevelTypeItem entity)
        {
            if (entity == null) return new LevelTypeModel();
    
            return new LevelTypeModel
            { 
                Id = entity.Id;
                IsDataCaptureRequired = entity.IsDataCaptureRequired;
                IsSetupRequired = entity.IsSetupRequired;
                IsApprover = entity.IsApprover;
                Name = entity.Name;
            }
        }
        public static IEnumerable ToModel(this IEnumerable entities)
        {
            if (entities== null) return new List();
    
            return (from e in entities
                    select e.ToModel());
        }
    
    }
    

    ...and you use them like this.....

     using (IUnitOfWork uow = new NHUnitOfWork())
            {
            IReadOnlyRepository repository = new NHRepository(uow);
            record = repository.Get(id);
    
            return record.ToModel();
    
            records = repository.GetAll(); // Return a collection from the DB
            return records.ToModel(); // Convert a collection of entities to a collection of models
            }
    

    Not perfect, but very easy to follow and very easy to reuse.

提交回复
热议问题