使用实体框架的 C# 中的通用存储库 [英] Generic Repository in C# Using Entity Framework

查看:28
本文介绍了使用实体框架的 C# 中的通用存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过提供主键数组来检索多条记录,我必须为所有实体创建通用方法.

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;
            }
        }

这里的问题是我的实体没有 ID 列,例如 Product 有 ProductId,Order 有 OrderId.我不想将我的 db 列更改为 Id.

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?

推荐答案

您可以使用 EF Core 提供的元数据服务,例如 FindEntityTypeFindPrimaryKey 以获取 PK 属性名称.然后,您可以使用它使用另一个 EF Core 提供的有用方法来访问 LINQ to Entities 查询中的 PK 值 EF.Property.

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.

像这样:

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();
}

这篇关于使用实体框架的 C# 中的通用存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆