c# - 基于非主键的EF核心查询

标签 c# asp.net-core ef-core-2.0 db-first

Net core 和 EF Core DB 第一种方法。我有一张表,它有 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(主键)获取国家/地区,但我想根据国家/地区名称进行查询。我正在想办法。有人可以指导我如何实现这一目标吗?任何帮助将不胜感激。谢谢

最佳答案

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

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

关于c# - 基于非主键的EF核心查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62281806/

相关文章:

c# - 如何获取从头到某个字符后的子串?

c# - 将分隔文件的读取从 F# 转换为 C#

docker - Visual Studio Dockerfile EntryPoint 覆盖解释?

c# - 在 asp.net core 中从 View 到 Controller 发布超过 1000 个值时,"InvalidDataException: Form value count limit 1024 exceeded."模型为空

c# - 使用包含相同 Entity MVC Core 的 1Entity 创建 Dbo

c# - Asp.net core 2.1 由于模型 InverseProperty 而崩溃

c# - 具有自定义列名称的同一表的外键

c# - tfs 站点服务器中出现 "Value cannot be null. Parameter name: key"问题

c# - FluentAssertions 检查对象字段是否不相等?

sql-server - ASP.NET Core Web API 服务无法连接到同一网络上的 Docker SQL Server