Last active
September 3, 2018 14:36
-
-
Save mota57/95df9ce0451f218bcb016305f3dcd7bf to your computer and use it in GitHub Desktop.
example of a base repository example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IModelClass | |
{ | |
public Guid Id {get; set;} | |
} | |
public class BaseRepository<TEntity, TDto> : IRepository<TEntity, TDto> | |
where TEntity : class, IModelClass | |
where TDto :class, IModelClass | |
{ | |
public IEnumerable<TEntity> Set { get; set; } | |
public InquiryContext context { get; set; } | |
public BaseRepository( InquiryContext context) | |
{ | |
this.context = context; | |
} | |
public virtual TEntity Add(TEntity entity) | |
{ | |
if(entity.Id == Guid.Empty) | |
{ | |
entity.Id = Guid.NewGuid(); | |
} | |
context.Set<TEntity>().Add(entity); | |
context.SaveChanges(); | |
return entity; | |
} | |
public virtual TEntity Find(Expression<Func<TEntity, bool>> expression = null) | |
{ | |
if (expression == null) | |
{ | |
expression = (TEntity f) => true; | |
} | |
return context.Set<TEntity>().FirstOrDefault(expression.Compile()); | |
} | |
public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> expression = null) | |
{ | |
if(expression == null) | |
{ | |
expression = (TEntity f) => true; | |
} | |
return context.Set<TEntity>().Where(expression.Compile()).ToList(); | |
} | |
public virtual TEntity Remove(TEntity entity) | |
{ | |
context.Entry(entity).State = EntityState.Deleted; | |
context.SaveChanges(); | |
return entity; | |
} | |
public virtual TEntity Update(TEntity entity) | |
{ | |
context.Entry(entity).State = EntityState.Modified; | |
context.SaveChanges(); | |
return entity; | |
} | |
public void Dispose() | |
{ | |
if(context != null) | |
{ | |
this.context = null; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment