一对多关系

发布时间 2023-09-20 17:49:31作者: 宁静致远.
  1. 必需的一对多
  2. 可选的一对多
  3. 具有阴影外键的必需的一对多
  4. 具有阴影外键的可选一对多

当单个实体与任意数量的其他实体关联时,将使用一对多关系。 例如,Blog 可以有多个关联的 Posts,但每个 Post 都只与一个 Blog 相关联。

必需的一对多

// Principal (parent)
public class Blog
{
    public int Id { get; set; }
    public ICollection<Post> Posts { get; } = new List<Post>(); // Collection navigation containing dependents
}

// Dependent (child)
public class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; } // Required foreign key property
    public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}