一对一关系建模器

本文关键字:建模 关系 一对一 | 更新日期: 2023-09-27 17:58:18

我正在尝试设置一对一的关系。请问我把这些字写在哪里?

modelBuilder.Entity<OfficeAssignment>() 
    .HasRequired(t => t.Instructor) 
    .WithOptional(t => t.OfficeAssignment);

非常感谢!

一对一关系建模器

您将在上下文类中的OnModelCreating方法中编写这些代码行

    public class MyContext : DbContext
    {
        public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<OfficeAssignment>() 
                        .HasRequired(t => t.Instructor) 
                        .WithOptional(t => t.OfficeAssignment);
            base.OnModelCreating(modelBuilder);
        }
    }

您可以在上下文类中编写,例如:

   public class AssignmentContext : DbContext
   {
      public IDbSet<OfficeAssignment> OfficeAssignments { get; set; }
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Entity<OfficeAssignment>() 
             .HasRequired(t => t.Instructor) 
             .WithOptional(t => t.OfficeAssignment);
          base.OnModelCreating(modelBuilder);
      }
   }