gpt4 book ai didi

entity-framework - EF4 CTP4 Code First 中带有附加列的连接表

转载 作者:行者123 更新时间:2023-12-03 07:34:02 24 4
gpt4 key购买 nike

给定这个 SQL 架构:

create table [dbo].[Courses_Students] (
[DummyColumn] [int] null,
[CourseId] [int] not null,
[StudentId] [int] not null,
primary key ([CourseId], [StudentId])
);

如何在 EntityConfiguration 中定义复合主键和附加列?

最佳答案

您需要声明一个类Courses_Students

public class Courses_Students
{
[Key]
public int CourseId { get; set; }
public int StudentId { get; set; }
public int DummyColumn { get; set; }

public virtual ICollection<Course> Courses { get; set; }
public virtual ICollection<Student> Students { get; set; }
}

CourseId 上的关键是为了防止编译错误,接下来您将覆盖它。

然后,在 DbContext 类中,您可以像这样重写 OnModelCreating :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Courses_Students>()
.HasKey(e => new { e.CourseId, e.StudentId })
.MapSingleType()
.ToTable("Courses_Students");
}

关于entity-framework - EF4 CTP4 Code First 中带有附加列的连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com