You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用一个Order模型类从两张关联表获取TypeName

问题:无需创建类型实体类获取关联的TypeName字段?

我有如下模型:

public class Order
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int TypeId { get; set; }
    public string TypeName { get; set; }
}

其中Id、Name和TypeId存储在Orders表中,TypeName因需多处复用存储在另一张Types表中,二者为一对多关联,TypeId是外键。类型表仅包含id和name两个字段。

我想了解是否无需创建Types表对应的模型类,就能获取TypeName,且最好能通过实体类型配置实现,避免每次查询都手动关联。

我尝试使用.SplitToTable()和.HasOne()但均未成功,以下是我使用.SplitToTable()的尝试代码:

public void Configure(EntityTypeBuilder<Order> builder)
{
    // 相关配置代码
    builder.ToTable("Orders");
    builder.HasKey(x => x.Id);
    builder.Property(x => x.ResourceTypeId);
    builder.SplitToTable("Types", tb =>
        {
            tb.Property(x => x.TypeName).HasColumnName("Name");
        });
}

编辑补充:感谢各位的评论!我最终为类型实体创建了ResourceType类,在Order中添加public ResourceType Type { get; set; }导航属性,并通过builder.Navigation(x => x.Type).AutoInclude()实现自动关联查询。


内容的提问来源于stack exchange,提问作者Fakima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:33:18