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

时间:2018-05-25 09:15:09

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

我正在使用.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:无法对null执行运行时绑定   引用CallSite.Target(Closure,CallSite,object)   System.Dynamic.UpdateDelegates.UpdateAndExecute1(调用点   网站,T0 arg0)   AspNetCore._Views_Requestor_Details_cshtml + d__8.MoveNext()   在Details.cshtml中   +                       @ email.Token.getStatusName()

1 个答案:

答案 0 :(得分:1)

要加载多个级别的相关数据,请使用here中记录的requirements.txt

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

ThenInclude