Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Repository in C# Using Entity Framework

I want to retrieve multiple records by giving array of primary key and I have to make generic method of it for all the entities.

private DbSet<TEntity> _entities;
      /// <summary>
            /// Get entity by identifier
            /// </summary>
            /// <param name="id">Identifier</param>
            /// <returns>Entity</returns>
            public virtual TEntity GetById(object id)
            {
                return Entities.Find(id);
            }




 /// <summary>
        /// Get entity by identifier
        /// </summary>
        /// <param name="id">Identifier</param>
        /// <returns>Entity</returns>
        public virtual List<TEntity> GetByIds(int id[])
        {
               // want to make it generic
            return Entities.Where(x=>id.Contains(id));
        }

    /// <summary>
        /// Gets an entity set
        /// </summary>
        protected virtual DbSet<TEntity> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<TEntity>();

                return _entities;
            }
        }

problem here is that my Entities doesn't have ID columns, for eg Product has ProductId, Order has OrderId. I don't want to change my db columns to Id.

Entities.Where(x=>id.Contains(id));

I want my entities columns to be same as they are now. can I achieve a generic search method with this db structure to find multiple records?

like image 851
Imran Ahmad Shahid Avatar asked Mar 04 '23 02:03

Imran Ahmad Shahid


1 Answers

You can use EF Core provided metadata services like FindEntityType and FindPrimaryKey to get the PK property name. Then you can use it to access the PK value inside LINQ to Entities query using another EF Core provided useful method EF.Property.

Something like this:

public virtual List<TEntity> GetByIds(int[] ids)
{
    var idName = _context.Model.FindEntityType(typeof(TEntity))
        .FindPrimaryKey().Properties.Single().Name;
    return Entities
        .Where(x => ids.Contains(EF.Property<int>(x, idName)))
        .ToList();
}
like image 168
Ivan Stoev Avatar answered Mar 13 '23 02:03

Ivan Stoev