多个“1到0..1”关系模型

时间:2012-02-28 09:36:46

标签: asp.net-mvc entity-framework-4 one-to-one

我正在使用microsoft的这个tutorial来创建一个与教师和OfficeAssignment之间的EF4.1的一对一关系。这就像一个魅力。

但是现在我想为每个教师添加一个Home(1到0或1),如下所示:

http://i.stack.imgur.com/ZmYur.png

我添加Home模型的方式与OfficeAssignment完全相同(如上面的教程中所示),但是当我尝试为这些模型添加控制器时,我收到错误“已经添加了一个具有相同名称的项目” 。

所以我的模型设置不正确。 下面有什么问题? 如何在EF4.1中创建多个一对一关系?

public class Instructor
{
    public Int32 InstructorID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public virtual OfficeAssignment OfficeAssignment { get; set; }
    public virtual Home Home { get; set; }
}

public class OfficeAssignment
{
    [Key]
    public int InstructorID { get; set; }
    public string Location { get; set; }
    public virtual Instructor Instructor { get; set; }
}

public class Home
{
    [Key]
    public int InstructorID { get; set; }
    public string Location { get; set; }
    public virtual Instructor Instructor { get; set; }
}

public class Context : DbContext
{
    public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
    public DbSet<Instructor> Instructors { get; set; }
    public DbSet<Home> Homes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

          modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
          modelBuilder.Entity<Instructor>()
            .HasOptional(p => p.OfficeAssignment)
            .WithRequired(p => p.Instructor);
          modelBuilder.Entity<Instructor>()
             .HasOptional(p => p.Home).WithRequired(p => p.Instructor);
}

1 个答案:

答案 0 :(得分:2)

看起来EF不支持真正的1到0..1关系。你需要一把外键。并将可选(int?)添加到主模型中。

所以我按照以下方式做了这个,它就像一个魅力。

public class Instructor
{
    public Int InstructorID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }

    public int? OfficeAssignmentID { get; set; }
    public virtual OfficeAssignment OfficeAssignment { get; set; }

    public int? HomeID { get; set; }
    public virtual Home Home { get; set; }

}

public class OfficeAssignment
{
    public int OfficeAssignmentID { get; set; }
    public string Location { get; set; }

}

public class Home
{
    public int HomeID { get; set; }
    public string Location { get; set; }
}