Ism*_*ael 6 entity-framework ef4-code-only
鉴于此sql架构:
create table [dbo].[Courses_Students] (
[DummyColumn] [int] null,
[CourseId] [int] not null,
[StudentId] [int] not null,
primary key ([CourseId], [StudentId])
);
Run Code Online (Sandbox Code Playgroud)
如何定义复合主键和其他列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; }
}
Run Code Online (Sandbox Code Playgroud)
CourseId上的Key是为了防止编译错误,接下来你将覆盖它.
然后,在您的DbContext类中,您重写OnModelCreating,如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Courses_Students>()
.HasKey(e => new { e.CourseId, e.StudentId })
.MapSingleType()
.ToTable("Courses_Students");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
797 次 |
| 最近记录: |