为什么使用ToListAsync没有结果?

时间:2018-07-11 17:37:08

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

我在此方面遇到了困难,希望您能为您提供帮助。

在我的GiftCertificateController.cs中(我在索引方法中使用了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()

1 个答案:

答案 0 :(得分: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);
}
相关问题