【问题标题】:Access entity through intermediate table with EF Core使用 EF Core 通过中间表访问实体
【发布时间】:2022-11-30 01:48:33
【问题描述】:

我目前正在使用 EF Core,我有 3 个表

Campaign
CampaignStation
Station

CampaignStationCampaignStation之间的中间表

活动表:

public class Campaign
{
    public int CampaignId { get; set; }

    public string Name { get; set; } = string.Empty;

    public ICollection<CampaignStation> Stations { get; set; } = new List<CampaignStation>();

 }

public void Configure(EntityTypeBuilder<Campaign> builder)
    {
        builder.HasKey(x => x.CampaignId);
        builder.Property(x => x.Name).IsRequired().HasMaxLength(250);
        builder.HasMany(x => x.Stations).WithOne(y => y.Campaign);
    }

所以一个活动可以有多个站,这就是为什么我有一个中间表作为:

public class CampaignStation
{
    public int CampaignStationId { get; set; }

    public int? CampaignId { get; set; }

    [ForeignKey(nameof(CampaignId))]
    public Campaign? Campaign { get; set; }

    public int? StationId { get; set; }

    [ForeignKey(nameof(StationId))]
    public Station? Station { get; set; }
}


public void Configure(EntityTypeBuilder<CampaignStation> builder)
    {
        builder.ToTable("CampaignStations");
        builder.HasKey(x => x.CampaignStationId);
        builder.HasOne(x => x.Campaign);
        builder.HasOne(x => x.Station);
    }

获取服务:

return await _db.Campaigns
            .Include(a => a.Agency)
            .Include(s => s.Stations)
            .ToListAsync();

但是 Stations 实体总是为 null,它正在获取中间表的 id,如下图所示:

为什么我无法访问 Station Entity?

【问题讨论】:

  • .Include(s =&gt; s.Stations).ThenInclude(cs =&gt; cs.Station)

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


【解决方案1】:

正如@vernou 的评论,我只需要添加中间表,然后使用ThenInclude 将 Station 表包括在内:

return await _db.Campaigns
            .Include(a => a.Agency)
            .Include(s => s.Stations)
            .ThenInclude(cs => cs.Station)
            .ToListAsync();

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 2022-11-30
    • 2010-09-29
    • 2021-05-14
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多