Search code examples
c#asp.net-coreef-core-2.0db-first

Ef core query based on non primary key


Net core and EF Core DB first approach. I have one table and It has Id which is primary key and one more countryname which is non primary key. I want to query country name and I will not be passing primary key. Below is my implementation.

IBaseRepository.cs

public interface IBaseRepository<T>
 {
  async Task<T> GetCountryByNameAsync(string country)
 }

BaseRepository.cs

public class BaseRepository<T>: IBaseRepository<T>
        where T : class
    {
      private readonly DbContext dbContext;
      private readonly DbSet<T> dbSet;
      public BaseRepository(DbContext dbContext)
        {
            this.dbContext = dbContext;
            this.dbSet = dbContext?.Set<T>();
        }
       public async Task<T> GetCountryByNameAsync(string country)
        {
            return await this.dbSet.FindAsync(id).ConfigureAwait(false); //This will return based on the countryId
            //I want select * from country where countryname = country
        }
    }

In the above implementation I can get country by id(primary key) but I want to query based on the countryname. I am trying to figure it out. Can someone guide me how we can accomplish this. Any help would be greatly appreciated. Thanks


Solution

  • If you want to get the first element with the provided country name use the FirstOrDefault method. Then Check if the returned value is null (Will return null in case countryName does not exist).

    public async Task<T> GetCountryByNameAsync(string country)
    {
        var country = await this.dbSet<T>.FirstOrDefault(c=>c.Countryname == country); 
        return country;
    }