简体   繁体   English

使用实体框架的C#中的通用存储库

[英]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. 这里的问题是我的实体没有ID列,例如Product有ProductId,Order有OrderId。 I don't want to change my db columns to Id. 我不想将我的数据库列更改为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? 我可以使用此db结构实现通用搜索方法来查找多条记录吗?

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: 您必须将Model Ids映射到数据库中的名称:

In your Mapping you will have something similar to this for every entity: this.Property(t => t.Id).HasColumnName("ProductId"); 在你的映射中,每个实体都有类似的东西:this.Property(t => t.Id).HasColumnName(“ProductId”);

You can use EF Core provided metadata services like FindEntityType and FindPrimaryKey to get the PK property name. 您可以使用EF Core提供的元数据服务(如FindEntityTypeFindPrimaryKey)来获取PK属性名称。 Then you can use it to access the PK value inside LINQ to Entities query using another EF Core provided useful method EF.Property . 然后,您可以使用它来访问LINQ to Entities查询中的PK值,使用另一个EF Core提供的有用方法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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM