Generic Repository in C# Using Entity Framework

.net .net-core c# entity-framework entity-framework-core

Question

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?

1
3
4/26/2019 12:31:23 PM

Accepted Answer

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();
}
3
4/27/2019 12:52:20 PM

Popular Answer

You can have different names in your application model and your database model. You will have to map your Model Ids to the name in database:

In your Mapping you will have something similar to this for every entity: this.Property(t => t.Id).HasColumnName("ProductId");



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow