繁体   English   中英

.net core EF FirstOrDefaultAsync 无法获取数据

[英].net core EF FirstOrDefaultAsync can not get data

我遇到一个奇怪的问题。 我使用.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很好,但我仍然不能。

发现问题了,Guid在数据库中必须是大写才能匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM