答案:在C#中使用EF Core配置实体关系需通过Fluent API或数据注解定义外键和导航属性。1. 一对多关系如用户与订单,通过HasOne-WithMany配置,外键位于“多”端;2. 一对一关系如用户与资料,使用HasOne-WithOne,外键放在依赖实体Profile中;3. 多对多关系自EF Core 5起支持自动创建中间表StudentCourses,也可自定义中间实体;4. 外键可空性决定关系是否可选,DeleteBehavior.Cascade可设置级联删除。推荐使用Fluent API以获得更灵活的配置控制。

在C#中使用EF Core配置实体之间的关系,核心是通过 Fluent API 或 数据注解(Data Annotations) 来定义外键和导航属性。下面介绍常见的一对多、一对一、多对多关系的配置方式以及外键的定义。
这是最常见的场景,比如一个“用户”可以有多个“订单”。
示例模型:<pre class="brush:php;toolbar:false;">public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public int UserId { get; set; } // 外键
public User User { get; set; } // 导航属性
}
<pre class="brush:php;toolbar:false;">protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasOne(o => o.User) // Order 拥有一个 User
.WithMany(u => u.Orders) // User 有多个 Order
.HasForeignKey(o => o.UserId); // 外键是 Order 的 UserId
}
<pre class="brush:php;toolbar:false;">public class Order
{
public int Id { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
public User User { get; set; }
}
例如,一个“用户”对应一个“用户资料”。
<pre class="brush:php;toolbar:false;">public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int Id { get; set; }
public int UserId { get; set; }
public string Bio { get; set; }
public User User { get; set; }
}
<pre class="brush:php;toolbar:false;">modelBuilder.Entity<User>()
.HasOne(u => u.Profile)
.WithOne(p => p.User)
.HasForeignKey<Profile>(p => p.UserId);
注意:一对一中,外键通常放在“依赖实体”上(这里是 Profile)。
例如,“学生”和“课程”是多对多关系。
<pre class="brush:php;toolbar:false;">public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public ICollection<Student> Students { get; set; }
}
<pre class="brush:php;toolbar:false;">modelBuilder.Entity<Student>()
.HasMany(s => s.Courses)
.WithMany(c => c.Students);
EF Core 会生成名为 StudentCourses 的中间表,包含 StudentsId 和 CoursesId 两个外键。
可以显式定义中间实体,并配置两个一对多关系。
控制外键是否允许为空,以及删除行为:
<pre class="brush:php;toolbar:false;">modelBuilder.Entity<Order>()
.HasOne(o => o.User)
.WithMany(u => u.Orders)
.HasForeignKey(o => o.UserId)
.OnDelete(DeleteBehavior.Cascade); // 删除用户时,其订单也被删除
如果外键是可空的(int?),则表示关系是可选的:
<pre class="brush:php;toolbar:false;">public int? UserId { get; set; } // 可选关系
以上就是C#中如何使用EF Core的关系配置?如何定义外键?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号