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/