Ich habe ein funktionierendes Repository.Hinzufügen zum Repository hinzufügen
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public TEntity Get(int id)
{
return Context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().Where(predicate);
}
public TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().SingleOrDefault(predicate);
}
public void Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
}
public void Remove(TEntity entity)
{
Context.Set<TEntity>().Remove(entity);
}
}
Wie ich in Coding-Repositorys lese, dass Sie keine Klasse hinzufügen, bis Sie es wirklich brauchen. Jetzt muss ich hinzufügen Include. Ich fand diese in dieser Gemeinschaft Use Include() method in repository:
public static class IncludeExtension
{
public static IQueryable<TEntity> Include<TEntity>(this IDbSet<TEntity> dbSet,
params Expression<Func<TEntity, object>>[] includes)
where TEntity : class
{
IQueryable<TEntity> query = null;
foreach (var include in includes)
{
query = dbSet.Include(include);
}
return query ?? dbSet;
}
}
Dann habe ich es in meinem Code zu passen (wie ich glaube) zu sein:
public IEnumerable<TEntity> Include(IDbSet<TEntity> dbSet,
params Expression<Func<TEntity, object>>[] includes)
{
IEnumerable<TEntity> query = null;
foreach (var include in includes)
{
query = dbSet.Include(include);
}
return query ?? dbSet;
}
Mit direktem Zugang zum Kontext, ich bin in der Lage zu schreiben:
Provinces = _cmsDbContext.Provinces.Include(c => c.District).Include(c => c.District.Country).ToList();
Aber mit Repository, kann ich nicht schreiben:
Provinces = Currentunitofwork.ProvinceRepository.Include(c => c.District).Include(c => c.District.Country).ToList();
Ich habe Fehler:
cannot convert lambda expression to type IDbSet<Province> because it is not a delegate type
Was ist das Problem hier ist, bitte.
Verwenden Sie System.Linq; und 'using System.Data.Entity;' in Ihrer Codedatei? – Ash
Wird diese Methode der Repository-Klasse hinzugefügt? –
@ Ashwin Nair. Ich benutze sie bereits, sonst wird auch bei direkter Verwendung von Kontext nicht funktionieren. –