一对多的关系总是让我空虚

时间:2019-10-03 10:58:58

标签: c# sql entity-framework foreign-keys relationship

我尝试先使用带有代码的Entity Framework和流利的api来实现一对多关系

我有两个班级

namespace Mantenimiento.Business.Entities
{
    public class Personal : Entity
    {
        [Key]
        public int Id { get; set; }
        public int? Dni { get; set; }
        public string Nombre { get; set; }
        public string Apellido { get; set; }

        public string Cuil { get; set; }
        public string Legajo { get; set; }

        [ForeignKey("Dni")]
        public  ICollection<ContactoEmergencia> Contacto { get; set; }
}

namespace Mantenimiento.Business.Entities
{
    public class ContactoEmergencia : Entity
    {
        [Key]
        public int Id { get; set; }
        public int? Dni { get; set; }
        public string ApellidoNombre { get; set; }
       public string Vinculo { get; set; }
        public string Domicilio { get; set; }
        public string telefono { get; set; }
        public string Comentario { get; set; }
        public int CreateUserId { get; set; }
        [ForeignKey("Dni")]
        public virtual Personal Personal { get; set; }
    }
}

这是我的dbContext

            #region personals
            modelBuilder.Entity<Personal>().ToTable("InfoPersonal").HasKey(t => t.Id);
            modelBuilder.Entity<Personal>().Property(c => c.Id).UseSqlServerIdentityColumn().IsRequired();
            modelBuilder.Entity<Personal>().Property(c => c.CreatedDate).HasDefaultValue(DateTime.Now);
            modelBuilder.Entity<Personal>().Property(c => c.LastModifiedDate).HasDefaultValue(DateTime.Now);
            modelBuilder.Entity<Personal>().Property(c => c.Deleted).HasDefaultValue(false);
            modelBuilder.Entity<Personal>().HasMany<ContactoEmergencia>(c => c.Contacto).WithOne(p => p.Personal).HasForeignKey(s => s.Dni);
#endregion
            #region contactoEmergencias
            modelBuilder.Entity<ContactoEmergencia>().ToTable("InfoEmergencia").HasKey(d => d.Dni);
            modelBuilder.Entity<ContactoEmergencia>().Property(c => c.CreatedDate).HasDefaultValue(DateTime.Now);
            modelBuilder.Entity<ContactoEmergencia>().Property(c => c.LastModifiedDate).HasDefaultValue(DateTime.Now);
            modelBuilder.Entity<ContactoEmergencia>().Property(c => c.Deleted).HasDefaultValue(false);
            #endregion

我的查询是

        return await _context.personals
            .Include(c => c.Contacto)
            .Where(p => p.Deleted == false)
            .OrderBy(s => s.Apellido)
            .ToListAsync(

);

但是属性始终为空。 我需要将Personal.Di与Contacto.Dni联系起来,我必须更改密钥吗?

1 个答案:

答案 0 :(得分:0)

您应该从“个人”实体中删除ForeignKey属性。在一对多关系中,只有子实体可以接受ForeignKey。