c# Code First Navigation在子元素上返回Null



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

请建议。使用E.F 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);
    }
}

更改映射:

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中的属性重命名为复数形式(地址,电话)。

最新更新