首页 > 解决方案 > IfExist 在通用存储库中

问题描述

我使用通用存储库和 unitofwork(.net core) 并尝试构建 IfExist 函数,

1:接口

 bool IsExistRecord<type>(type Id);

2- 实施

 public bool IsExistRecord<type>(type Id)
    {
        var query = DbSet.Find(Id);
        if (query != null)
        {
            return true;
        }

        return false;
    }

3-使用它。

_unitOfWork.GetRepository<EntityName>().IsExistRecord(id);

但在这种情况下,我尝试只检查表的主键,
如何检查表中的任何列作为代码,名字?!任何帮助

标签: generics.net-corerepository-pattern

解决方案


您只需要为您的存储库提供这样的扩展方法(或者您可以将其转换并直接添加到存储库)

    /// <summary>
    /// Gets a value indicating whether or not the record exists by query
    /// </summary>
    /// <param name="repository">Repository Instance</param>
    /// <param name="predicate">Query Predicate</param>
    /// <returns>True if the object exists</returns>
    public static bool DoesExist<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return repository.Get(p => p.Where(predicate)).FirstOrDefault() != null;
    }

然后像这样调用它:

_unitOfWork.GetRepository<EntityName>().DoesExist(p => p.FirstName == "Robert");

推荐阅读