0

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(主键)获取国家,但我想根据国家名称进行查询。我试图弄清楚。有人可以指导我如何做到这一点。任何帮助将不胜感激。谢谢

4

2 回答 2

2

如果要获取具有提供的国家名称的第一个元素,请使用该FirstOrDefault方法。然后检查返回值是否为(如果不存在则null返回null )。countryName

public async Task<T> GetCountryByNameAsync(string country)
{
    var country = await this.dbSet<T>.FirstOrDefault(c=>c.Countryname == country); 
    return country;
}
于 2020-06-09T11:51:28.487 回答
1

只需使用 FirstOrDefaultAsync

    public async Task<T> GetCountryByNameAsync(string country)
    {
        return await this.dbSet<Country>.FirstOrDefaultAsync(c=>c.Countryname == country).ConfigureAwait(false); 
    }
于 2020-06-09T11:48:02.060 回答