.net核心EF FirstOrDefaultAsync无法获取数据

时间:2020-03-23 10:23:49

标签: c# asp.net-core-3.1 .net-core-3.1

我遇到一个奇怪的问题。我使用.net core 3.1,pkg是Microsoft.EntityFrameworkCore,DB是Sqlite

我的实体:

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Introduction { get; set; }
}

处理程序接口:

public interface ICompanyRepository
{
    Task<IEnumerable<Company>> GetCompaniesAsync();
    Task<Company> GetCompanyAsync(Guid companyId);
    Task<bool> CompanyExistsAsync(Guid companyId);
}

当我实现以下方法时,只有第一个GetCompaniesAsync返回数据,其他返回null:

// This method can be return data
public async Task<IEnumerable<Company>> GetCompaniesAsync()
{
    return await _context.Companies.ToListAsync();
}

// This method return null
public async Task<Company> GetCompanyAsync(Guid companyId)
{
    if (companyId == Guid.Empty)
    {
        throw new ArgumentNullException(nameof(companyId));
    }

    return await _context.Companies.FirstOrDefaultAsync(x => x.Id == companyId);
}

// This method also return null
public async Task<bool> CompanyExistsAsync(Guid companyId)
{
    if (companyId == Guid.Empty)
    {
        throw new ArgumentNullException(nameof(companyId));
    }

    return await _context.Companies.AnyAsync(x => x.Id == companyId);
}

我试图删除await

public async Task<Company> GetCompanyAsync(Guid companyId)
{
    if (companyId == Guid.Empty)
    {
        throw new ArgumentNullException(nameof(companyId));
    }

    foreach (var c in _context.Companies.ToList())
    {
        if (c.Id == companyId)
        {
            return c;
        }
    }

    return null;
}

它可以返回普通数据,而不是null

以下是在控制器中调用的方法:

public async Task<Company> GetCompany(Guid companyId)
{
    var company = await companyRepository.GetCompanyAsync(companyId);
    if (company == null)
    {
        return NotFound();
    }
    return Ok(company);
}

头脑中有using Microsoft.EntityFrameworkCore;

此外,我已经看到有人说安装Microsoft.EntityFrameworkCore.Tools很好,但是我仍然做不到。

1 个答案:

答案 0 :(得分:0)

我发现了问题,Guid必须在数据库中为大写字母。