Reputation: 903
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
Upvotes: 2
Views: 1745
Reputation: 3486
Just use FirstOrDefaultAsync
public async Task<T> GetCountryByNameAsync(string country)
{
return await this.dbSet<Country>.FirstOrDefaultAsync(c=>c.Countryname == country).ConfigureAwait(false);
}
Upvotes: 1
Reputation: 1695
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;
}
Upvotes: 2