Search code examples
c#asp.net-core-mvc

Find By Full Name Or Email in Find Method Generic Repository?


I Want Use Full Name Or Email Instead Of Id For Search in Find Method in Generic Repsoitory ? How Can Search With FullName in Find Method Instead Of Id? This is FindById Method

    public async Task<T> GetByIdAsync(object Id)
    {
        return await _dbContext.Set<T>().FindAsync(Id);
    }

I Want Search In Code Above With Full Name?


Solution

  • You can add a generic function to your repository, like this:

    public T FindBy(Expression<Func<T, bool>> predicate)
    {
        return Context.Set<T>().Where(predicate).FirstOrDefault();
    }
    

    And then in your program, call it like this:

    var person1 = MyGenericRepository.FindBy(r => r.FullName == "John Smith");
    var person2 = MyGenericRepository.FindBy(r => r.Email == "jane.smith@gmail.com");
    

    Assuming you have FullName and Email in your DB Set.