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

一对一关系下通过特性配置父实体的子实体导航属性

基于特性配置EF Core一对一关联(Parent含Child导航属性)

实体类配置代码

Parent实体(包含指向Child的导航属性)

public class Parent
{
    public int Id { get; set; }
    // 自定义业务属性示例
    public string ParentName { get; set; }

    // Parent指向Child的导航属性,通过InverseProperty关联Child的Parent导航属性
    [InverseProperty(nameof(Child.Parent))]
    public Child ChildNavigationProp { get; set; }
}

Child实体(包含指向Parent的外键及导航属性)

using System.ComponentModel.DataAnnotations.Schema;

public class Child
{
    public int Id { get; set; }
    // 自定义业务属性示例
    public string ChildName { get; set; }

    // 指向Parent的外键字段
    public int ParentId { get; set; }

    // Child指向Parent的导航属性,通过ForeignKey指定关联的外键字段
    [ForeignKey(nameof(ParentId))]
    public Parent Parent { get; set; }
}

可选:确保严格一对一关系

如果需要在数据库层面强制一个Parent只能对应一个Child,可给Child的ParentId字段添加唯一索引特性:

using System.ComponentModel.DataAnnotations.Schema;

public class Child
{
    public int Id { get; set; }
    public string ChildName { get; set; }

    [Index(IsUnique = true)] // 添加唯一索引,保证外键唯一
    public int ParentId { get; set; }

    [ForeignKey(nameof(ParentId))]
    public Parent Parent { get; set; }
}

查询用法

配置完成后,即可使用你需要的Include查询写法:

var parentsWithChildren = context.Set<Parent>().Include(p => p.ChildNavigationProp).ToList();

特性说明

  • [ForeignKey]:指定导航属性对应的外键字段,明确Child的Parent导航属性关联的是ParentId字段
  • [InverseProperty]:明确双向导航的对应关系,告诉EF Core Parent的ChildNavigationProp和Child的Parent是同一对关联的两端,避免自动识别错误
  • [Index(IsUnique = true)]:可选,在数据库层面创建唯一索引,确保ParentId不重复,严格保证一对一关系

内容的提问来源于stack exchange,提问作者Branislav B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:38:27