如何在entityFrameWorkCore中加载相关数据?

时间:2019-09-18 11:51:16

标签: asp.net-core model-view-controller entity-framework-core linq-to-entities

我想从地址表中获取相关数据,但不起作用,并且电话的结果数为零。 我的加载数据代码如下:

var address = table.Include(e=>e.Phones).FirstOrDefault();

我有2个表,具有如下关系:

    public class Phone:BaseEntity
    {
    public string PhoneNumber { get; set; }
        #region Relations
        public int KindId { get; set; }
        public virtual PhoneKind PhoneKind { get; set; }
        public int? AddressId { get; set; }
        [ForeignKey("AddressId")]
        public virtual Address Address { get; set; }
        public int ContactId { get; set; }
        public virtual Contact Contact { get; set; }
 #endregion
}


   public class Address : BaseEntity
    {
        public AddressKindEnum Kind { get; set; }
        public string Range { get; set; }
        public string MainStreet { get; set; }
        public string Street { get; set; }
        public string HouseNumber { get; set; }
        public string BuildingName { get; set; }
        public string Ring { get; set; }
        public string Floor { get; set; }
        public string Unit { get; set; }
        public string Description { get; set; }
        public string Region { get; set; }
        public string Zone { get; set; }
        public bool IsIncomplete { get; set; }
        public bool IsDefault { get; set; }
        public DateTime CreatedTime { get; set; }
        public bool IsDeleted { get; set; }

        #region Relations
        public int? CountryId { get; set; }
        public virtual Country Country { get; set; }

        public int? StateId { get; set; }
        public virtual State State { get; set; }
        public int? CityId { get; set; }
        public virtual City City { get; set; }

        public int ContactId { get; set; }
        public virtual Contact Contact { get; set; }


        public virtual ICollection<Phone> Phones { get; set; } = new List<Phone>();
        #endregion


    }

和我在ApplicationDbContext中的代码如下:

modelBuilder.Entity<Phone>()
                .HasOne(e => e.Address)
                .WithMany(c => c.Phones)
                .HasForeignKey(e=>e.AddressId)
                .IsRequired(false);

0 个答案:

没有答案