基于非主键的Ef核心查询

问题描述 投票:0回答:2

网络核心和EF核心数据库优先方法。我有一张表,它有一个ID是主键,还有一个国家名是非主键。我想查询国家/地区名称,并且不会传递主键。下面是我的实现。

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

c# asp.net-core ef-core-2.0 db-first
2个回答
3
投票

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

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

0
投票

只需使用FirstOrDefaultAsync

© www.soinside.com 2019 - 2024. All rights reserved.