Daten können hinzugefügt
This commit is contained in:
80
KanSan.Base/BaseRepository.cs
Normal file
80
KanSan.Base/BaseRepository.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
using KanSan.Base.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace KanSan.Base
|
||||
{
|
||||
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
|
||||
{
|
||||
internal KanSanContext context;
|
||||
internal DbSet<TEntity> dbSet;
|
||||
|
||||
public BaseRepository(KanSanContext context)
|
||||
{
|
||||
this.context = context;
|
||||
if (context == null) throw new ArgumentNullException("context");
|
||||
this.dbSet = context.Set<TEntity>();
|
||||
}
|
||||
public virtual void Delete(TEntity entityToDelete)
|
||||
{
|
||||
if (context.Entry(entityToDelete).State == EntityState.Detached)
|
||||
dbSet.Attach(entityToDelete);
|
||||
dbSet.Remove(entityToDelete);
|
||||
}
|
||||
|
||||
public void Delete(object id)
|
||||
{
|
||||
TEntity entityToDelete = dbSet.Find(id);
|
||||
Delete(entityToDelete);
|
||||
}
|
||||
|
||||
public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
|
||||
{
|
||||
IQueryable<TEntity> query = dbSet;
|
||||
|
||||
if (filter != null)
|
||||
{
|
||||
query = query.Where(filter);
|
||||
}
|
||||
|
||||
if (includeProperties != null)
|
||||
{
|
||||
foreach (var includeProperty in includeProperties.Split
|
||||
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
query = query.Include(includeProperty);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (orderBy != null)
|
||||
{
|
||||
return orderBy(query).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public TEntity GetByID(object id)
|
||||
{
|
||||
return dbSet.Find(id);
|
||||
}
|
||||
|
||||
public virtual void Insert(TEntity entity)
|
||||
{
|
||||
dbSet.Add(entity);
|
||||
}
|
||||
|
||||
public void Update(TEntity entityToUpdate)
|
||||
{
|
||||
dbSet.Attach(entityToUpdate);
|
||||
context.Entry(entityToUpdate).State = EntityState.Modified;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user