【问题标题】:Ef core query based on non primary key基于非主键的ef核心查询
【发布时间】:2020-09-28 14:00:18
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    如果您想获取具有所提供国家名称的第一个元素,请使用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.countryname,它显示选项 equals、gethashcode、gettype 和 tostring
    • 现在检查代码我忘记了泛型类型。还有一件事,泛型类型 T。应该扩展一个类,其中该类包含一个名为 countryName 的属性。你明白我的意思了吗?
    • 因为现在,我们使用的泛型类型T 包含一个名为countryName 的属性
    【解决方案2】:

    只需使用 FirstOrDefaultAsync

        public async Task<T> GetCountryByNameAsync(string country)
        {
            return await this.dbSet<Country>.FirstOrDefaultAsync(c=>c.Countryname == country).ConfigureAwait(false); 
        }
    

    【讨论】:

    • 感谢您的回答。我无法获得 C.countryname,它显示选项 equals、gethashcode、gettype 和 tostring
    • 啊通常你应该在你的 DbContext 上有一个 DbSet 或类似的东西......我怀疑你必须创建一个 CountryRepository : BaseRepository
    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2020-10-09
    相关资源
    最近更新 更多