[英]Ef core query based on non primary key
Net core 和 EF Core DB 第一種方法。 我有一張表,它的 Id 是主鍵,還有一個 countryname 是非主鍵。 我想查詢國家名稱,我不會傳遞主鍵。 下面是我的實現。
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
}
}
在上述實現中,我可以通過 id(主鍵)獲取國家,但我想根據國家名稱進行查詢。 我試圖弄清楚。 有人可以指導我如何做到這一點。 任何幫助將不勝感激。 謝謝
如果要獲取具有提供的國家名稱的第一個元素,請使用FirstOrDefault
方法。 然后檢查返回值是否為null
(如果countryName
不存在,將返回 null)。
public async Task<T> GetCountryByNameAsync(string country)
{
var country = await this.dbSet<T>.FirstOrDefault(c=>c.Countryname == country);
return country;
}
只需使用 FirstOrDefaultAsync
public async Task<T> GetCountryByNameAsync(string country)
{
return await this.dbSet<Country>.FirstOrDefaultAsync(c=>c.Countryname == country).ConfigureAwait(false);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.