1

导航工作从地址、电话到人员。我无法让人们获得任何导航属性到地址或电话。我在 people 中的导航属性显示电话和地址为 null。

请指教。使用 EF 4.5

public class Person
{
    [Key]
    public int PersonID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", this.FirstName, this.LastName);
        }
    }
    public string Email { get; set; }
    public virtual ICollection<Address> Address { get; set; }
    public virtual ICollection<Phone> Phone { get; set; }
}

public class Phone
{
    [Key]
    public int PhoneID { get; set; }
    public int PersonID { get; set; }
    public virtual Person Person { get; set; }
    [Required]
    public string PhoneNum { get; set; }
    [Required]
    public int PhoneNumTypeID { get; set; }
}

public class Address
{
    [Key]
    public int AddressID { get; set; }
    public int PersonID { get; set; }
    public virtual Person Person { get; set; }
    [Required]
    public string Street { get; set; }
    public int AddressTypeID { get; set; }
    public virtual AddressType AddressType { get; set; }
}

public class AddressType
{
    [Key]
    public int AddressTypeID { get; set; }

    [Required]
    public string AddressTypeDesc { get; set; }
}

public class ContactContext : DbContext
{
    public ContactContext() : base("Contact") { }
    public DbSet<Person> People { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Phone> Phones { get; set; }
    public DbSet<AddressType> AddressTypes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>()
            .HasRequired(x => x.Person)
            .WithMany()
            .HasForeignKey(x => x.PersonID);

        modelBuilder.Entity<Phone>()
            .HasRequired(x => x.Person)
            .WithMany()
            .HasForeignKey(x => x.PersonID);

        modelBuilder.Entity<Address>()
            .HasRequired(x => x.AddressType)
            .WithMany()
            .HasForeignKey(x => x.AddressTypeID);

        base.OnModelCreating(modelBuilder);
    }
}
4

1 回答 1

0

更改映射:

modelBuilder.Entity<Address>()
    .HasRequired(x => x.Person)
    .WithMany(p => p.Address)         // changed here
    .HasForeignKey(x => x.PersonID);

modelBuilder.Entity<Phone>()
    .HasRequired(x => x.Person)
    .WithMany(p => p.Phone)         // changed here
    .HasForeignKey(x => x.PersonID);

顺便说一句,我会将属性重命名Person为复数形式(地址、电话)。

于 2013-03-01T08:41:31.017 回答