
深入解析API网关策略:认证、授权、安全、流量处理与可观测性
多对多关系(N\:N)指的是两个实体之间可以互相关联多条记录,如学生与课程、Pokemon 与 Owner 互为多对多。实现此关系需借助Join 实体(关联表),本文基于 Pokémon 示例详解实现过程。
Pokemon
── Owner
与 Pokemon
── Category
,都需通过中间表实现。在 Models
内新增 PokemonOwner.cs
:
public class PokemonOwner
{
public int PokemonId { get; set; }
public Pokemon Pokemon { get; set; }
public int OwnerId { get; set; }
public Owner Owner { get; set; }
}
同理创建 PokemonCategory.cs
:
public class PokemonCategory
{
public int PokemonId { get; set; }
public Pokemon Pokemon { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
Join 表同时持有两个外键和对应导航属性,用于存储多对多关系。
Pokemon 类新增:
public ICollection < PokemonOwner > PokemonOwners { get; set; }
public ICollection < PokemonCategory > PokemonCategories { get; set; }
Owner 类新增:
public ICollection < PokemonOwner > PokemonOwners { get; set; }
Category 类新增:
public ICollection < PokemonCategory > PokemonCategories { get; set; }
通过集合导航属性,EF Core 可识别并查询关联数据。
通过本篇,您已掌握手动构建 N\:N 关系的核心步骤,为更复杂的数据模型打下坚实基础。
原文引自YouTube视频:https://www.youtube.com/watch?v=oOUSvRc3FMo