EF:一对一的关系

时间:2012-10-02 15:38:13

标签: c# asp.net-mvc-3 entity-framework one-to-one

我正在尝试建立双向一对一的关系。但是,我无法获得两个实体的双向设置。

例如,假设一个人有一个电话号码,一个电话号码只能与一个人关联。我会:

  public class Person : Entity
  {
    public long PersonId { get; set; }
    public virtual PhoneNumber PhoneNumber {get; set; }
  }

  public class PhoneNumber : Entity
  {
    public long PhoneNumberId { get; set; }
  }

然而,通过这种重新安排,我无法获得双向设置。即我不能phoneNumber.Person.


我尝试了什么:

  public class PhoneNumber : Entity
  {
    public long PhoneNumberId { get; set; }

    [InverseProperty("PersonId")]
    public virtual Person Person {get; set; }
  }

当我执行以下代码时,这似乎不起作用:

   var realNumber = new PhoneNumber();
   var person = new Person() {PhoneNumber = realNumber};
   context.SaveChanges();

这里,PhoneNumber实体有一个Person列(设置为NULL),该人有一个PhoneNumber列(有值)。

1 个答案:

答案 0 :(得分:1)

这对我有用

namespace Ef1to1
{
    public class TestContext : DbContext
    {

        public TestContext()
            : base("Data Source=127.0.0.1;database=Junk;Integrated Security=SSPI;")
        {

        }
        public DbSet<Person> Persons { get; set; }
        public DbSet<PhoneNumber> PhoneNumbers { get; set; }
    }
    [Table("Person")]
    public class Person 
    {
        [Key, Column("PersonId")]
        public long Id { get; set; }

        public virtual PhoneNumber phoneNumber { get; set; }
    }

    [Table("PhoneNumber")]
    public class PhoneNumber
    {

        [Key, Column("PhoneNumberId"), ForeignKey("person")]
        public long Id { get; set; }

        public virtual Person person { get; set; }
    } 

   public class Program
    {

        static void Main(string[] args)
        {
            var realNumber = new PhoneNumber();
            var person = new Person() { phoneNumber = realNumber }; 
            var context = new TestContext();

            context.Persons.Add(person) ;
            context.SaveChanges();
            ;

        }
    }
}