【问题标题】:.NET Core 5 Table Per Type Inheritance Includes.NET Core 5 表每种类型继承包括
【发布时间】:2021-07-12 08:56:07
【问题描述】:

我正在尝试使用 Table Per Type Inheritance 策略检索数据。我有一个表“Teams”扩展表“Groups”,其中 Groups 有一个指向“Tenant”表的链接。当我尝试这样做时:

var org = await _context.Tenant.Include(t => t.Teams)
                        .FirstOrDefaultAsync(t => t.Id == tenantId);

我无法返回团队。

我的团队和小组模型如下所示:

    [Table("Groups")]
    public class Group
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<GroupUser> GroupUsers { get; set; }

        public int? TenantId { get; set; }
        public Tenant Tenant { get; set; }
    }


    [Table("Teams")]
    public class Team : Group
    {
        public string TeamManagerId { get; set; }
        public ApplicationUser TeamManager { get; set; }
    }

在上下文中,我有这个组:

 modelBuilder.Entity<Group>(entity =>
            {
                entity.HasOne(x => x.Tenant)
                    .WithMany(t => t.Clusters)
                    .HasForeignKey(x => x.TenantId)
                    .IsRequired(false)
                    .OnDelete(DeleteBehavior.Restrict);  
            });

然后团队什么都不返回,如果我将团队更改为组(在查询中)它会起作用,正如人们所期望的那样。我意识到这可能与上下文中上述组的连接设置有关,但不确定如果有什么可以为团队放置什么,因为它没有直接链接到租户表,它的连接应该是通过组。

我如何返回团队?

非常感谢

埃蒙

【问题讨论】:

  • 都属于“Tenant”表 - 这个描述是错误的,你应该用正确的词来谈论实体之间的关系。为了清楚起见,您应该包括详细的实体类,分别编写工作查询和非工作查询......我们通常不喜欢猜测这些事情,尽管在某些情况下我们可能能够猜测到。

标签: .net asp.net-core .net-core entity-framework-core asp.net-core-5.0


【解决方案1】:

你想得到这个小组和它的子模型团队吗?

您应该添加团队和租户之间的关系,而不是组和租户。

查看我的演示:

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }          
}

public class Team : Group
{
    public string TeamManagerId { get; set; }
    public int? TenantId { get; set; }
    public Tenant Tenant { get; set; }
}

public class Tenant
{
    public int TenantId { get; set; }
    public string Name { get; set; }

    public List<Team> Teams { get; set; }
}

然后是linq;

var model = _context.Tenants.Include(x => x.Teams).ToList();

使用方法:

@model IEnumerable<Tenant>

@foreach (var item in Model)
 {
     foreach (var item2 in item.Teams)
    {
        @item2.Name; //group property
        @item2.TeamManagerId; //team property
    }
 }

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多