C# EntityFramework 包含引用及其引用,如何?

C# EntityFramework Include reference and its references, how?

我正在使用 .NET Core 2.0

我有 3 个模型:

class ModelA {
    [Key]
    public int ID { get; set; }
    public List<ModelB> Emails { get; set; }
}

class ModelB {
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public int RequestId { get; set; }
    public ModelA Request { get; set; }
    public List<ModelC> Tokens { get; set; }
}

class ModelC {
    [Key]
    public int ID { get; set; }
    public string Token { get; set; }
    public int Status { get; set; }

    public string getStatusName()
    {
        string[] Statuses = new string[] {
            "Created",      // 0
            "Approved",     // 1
            "Rejected"      // 2
        };

        return Statuses[Status];
    }
}

我也有这样创建的上下文:

public class RequestorContext : DbContext
{
    public DbSet<ModelA> Request { get; set; }
    public DbSet<ModelB> Email { get; set; }
    public DbSet<ModelC> Token { get; set; }

    public RequestorContext(DbContextOptions<RequestorContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

现在我想在控制器中做这样的事情:

var request = await _context.Request
                .Include(r => r.Emails) //also include tokens - how ???
                .SingleOrDefaultAsync(r => r.Id == id);

那么基本上如何将相应的令牌包含到电子邮件中? 能够在视图中做这样的事情:

@foreach (var email in Model.Emails)
{
    <tr>
        <td>@email.Name</td>
        <td>@email.Token.Token</td>
        <td>@email.Token.getStatusName()</td>
    </tr>
}

目前我收到这样的错误:

RuntimeBinderException: Cannot perform runtime binding on a null reference CallSite.Target(Closure , CallSite , object ) System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) AspNetCore._Views_Requestor_Details_cshtml+d__8.MoveNext() in Details.cshtml + @email.Token.getStatusName()

要加载多个级别的相关数据,请使用 ThenInclude 作为记录 here

要解决您的问题,您的代码应如下所示:

var request = await _context.Request
            .Include(r => r.Emails)
            .ThenInclude(e => e.Tokens)
            .SingleOrDefaultAsync(r => r.Id == id);