1

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

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

  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),而 person 有一列 PhoneNumber(有值)。

4

1 回答 1

2

这对我有用

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();
            ;

        }
    }
}
于 2012-10-02T15:55:59.310 回答