多对多Ef核心

时间:2020-11-11 08:24:36

标签: c# .net-core entity-framework-core many-to-many

因此在我的API中,我有以下模型:Doctors,Pacients和Appointments(但我认为我们应该忽略这一模型)。我很好地完成了Doctors和Pacients之间的多对多关系(我认为),就像他们在msdocs上所说的一样。

创建实体DoctorPacient并将此属性添加到Pacient和Doctor模型中之后


    public List<DoctorPacient> DoctorsPacients { get; set; } 

这是DoctorPacient实体的外观

    public class DoctorPacient
    {
        
        public int DoctorId { get; set; }
        public Doctor Doctor { get; set; }
        public int PacientId { get; set; }
    
        public Pacient Pacient { get; set; }
    }    

在数据库上下文中,我有以下内容

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<DoctorPacient>()
                .HasKey(dp => new { dp.DoctorId, dp.PacientId });  
                
            modelBuilder.Entity<DoctorPacient>()
                .HasOne(dp => dp.Doctor)
                .WithMany(d => d.DoctorsPacients)
                .HasForeignKey(dp => dp.DoctorId);  
    
            modelBuilder.Entity<DoctorPacient>()
                .HasOne(dp => dp.Pacient)
                .WithMany(p => p.DoctorsPacients)
                .HasForeignKey(dp => dp.PacientId);
         }

当我尝试将其放入存储库中时,它不起作用

public IEnumerable<Pacient> GetPacients(int doctorId)
        {
               if (doctorId == 0)
            {
                throw new ArgumentNullException(nameof(doctorId));
            }

            var pacient = _context.Pacients.ToList();

            return pacient.Where(p=>p.DoctorsPacients.DoctorId == doctorId );
        }

这是错误

'列表'不包含'DoctorId'的定义,并且找不到可访问的扩展方法'DoctorId'接受类型为'List '的第一个参数(您是否缺少using指令或程序集参考?)。

0 个答案:

没有答案