【问题标题】:Why does using ToListAsync yield no results?为什么使用 ToListAsync 没有结果?
【发布时间】:2018-12-19 20:12:24
【问题描述】:

我很难处理这个问题,所以我希望你能提供帮助。

在我的 GiftCertificateController.cs 中(我在 index 方法中使用了 LINQ 查询)

private readonly VoucherDbContext _context;

    public GiftCertificateController(VoucherDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        var gifts = _context.GiftCertificates
            .Include(e => e.VoucherCampaigns)
            .Include(e => e.CouponBrand)
            .Include(e => e.CouponTypes);

        return View(await gifts.ToListAsync());
    }

然而,现在在调试期间,将鼠标悬停在“gifts.ToListAsync”上会显示“Ienumerable:枚举未产生任何结果”。

奇怪的是我对 3 个不同的控制器使用完全相同的模式(相同的业务实体结构、相同的实体映射结构、相同的视图结构),它们似乎都工作正常,但特别是对于这个控制器,它不是能够显示单个数据库属性。 (该表有 30+ 行)

这是企业实体 GiftCertificates.cs 的摘录:

public partial class GiftCertificates
{
    [Key]
    public int Id { get; set; }
    public string CertificateId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal? CertificateAmount { get; set; }
    public decimal? CertificateValue { get; set; }
    public int? TypeId { get; set; }
    public int? CategoryId { get; set; }
    public int? BrandId { get; set; }

    [ForeignKey("CampaignId")]
    public VoucherCampaigns VoucherCampaigns { get; set; }
    [ForeignKey("TypeId")]
    public CouponTypes CouponTypes { get; set; }
    [ForeignKey("BrandId")]
    public CouponBrand CouponBrand { get; set; }

}

这是我的 DbContext 中实体映射的摘录:

entity.ToTable("CertificateMaster");

            entity.Property(e => e.Id)
            .IsRequired()
            .HasColumnName("Id");

            entity.Property(e => e.CampaignId)
            .HasColumnName("CampaignId");

            entity.Property(e => e.CertificateId)
            .HasColumnName("CertificateId");

SQL中的数据库表名是dbo.CertificateMaster。

非常感谢任何帮助。谢谢!

编辑:Debug gift.ToListAsync()

【问题讨论】:

  • 我不确定将鼠标悬停在“gifts.ToListAsync()”上是否是检查结果的正确方法,因为它是异步的并且涉及“包含”语句,因此请尝试在单独的线;比如: var giftList = await gift.ToListAsync() 然后检查 giftList 的值。
  • 我按照你说的做了,我认为这不是问题,因为在调试模式下,在其他工作控制器中,我可以通过将鼠标悬停在 var.ToListAsync() 上来查看 db 属性。尽管它不在变量中。我已经用您建议的输出编辑了原始问题。
  • 您能否与我们分享一个演示项目来重现您的问题,因为它似乎更特定于该控制器?

标签: c# linq asp.net-core-mvc entity-framework-core


【解决方案1】:

理想情况下,您希望先等待结果,然后将其传递给视图

public async Task<IActionResult> Index() {
    var gifts = await _context.GiftCertificates
        .Include(e => e.VoucherCampaigns)
        .Include(e => e.CouponBrand)
        .Include(e => e.CouponTypes)
        .ToListAsync();

    return View(gifts);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多