Mediator
Mediator

Reputation: 15378

How add method get by ID?

I have general class. I need create method get seingleOrDefault by ID?

How to do this?

public T GetByID(int id)
{
    _entities.Set<T>().Single(x => x.);
}

general class:

   public abstract class GenericRepository<C, T> : IGenericRepository<T>
        where T : class
        where C : DbContext, new()
    {

        private C _entities = new C();
        public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }

        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {

            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }

        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = System.Data.EntityState.Modified;
        }

        public virtual void Save()
        {
            _entities.SaveChanges();
        }
    }

Upvotes: 0

Views: 681

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

If you are using DbContext then method Set<T>() returns DbSet<T> instead of ObjectSet<T>. DbSet<T> has method DbSet<T>.Find(params object[] keyValues) which does exactly what you are trying to implement:

This method uses the primary key value to attempt to find an entity tracked by the context. If the entity is not in the context then a query will be executed and evaluated against the data in the data source, and null is returned if the entity is not found in the context or in the data source.

Usage:

public T GetByID(int id)
{
    return _entities.Set<T>().Find(id);
}

Upvotes: 3

khellang
khellang

Reputation: 18102

If you want to do this in a generic fashion, you need to add a generic constraint on T.

Something like

public interface IEntity
{
    int Id { get; set; }
}

public abstract class GenericRepository<C, T> : IGenericRepository<T>
    where T : class, IEntity
    where C : DbContext, new()
{
    public T GetByID(int id)
    {
        _entities.Set<T>().SingleOrDefault(x => x.Id == id);
    }

    ...

}

Upvotes: 0

Related Questions