在广泛阅读本主题后,我想实现自己的多对多关系。这是我的用例:
仅供参考:虽然 和之间没有 FK 关系
Program
,并且充当关系列Provider
Program.ProvID
Provider.ProvID
在我的 DAL 中,我有以下模型:
public class Patient
{
public Patient()
{
Programs = new HashSet<Program>();
}
public virtual ICollection<Program> Programs { get; set; }
}
public class Program
{
public Program()
{
Patients = new HashSet<Patient>();
Organization = new HashSet<Organization>();
}
public int ProgramId { get; set; }
public string Name { get; set; }
public string SiteName { get; set; }
public int ProviderId { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
public virtual ICollection<Organization> Organization { get; set; }
}
public class Organization
{
public Organization()
{
Programs = new HashSet<Program>();
}
public int OrgID { get; set; }
public string Name { get; set; }
public virtual ICollection<Program> Programs { get; set; }
}
在我的AppContext
我将这些模型映射如下:
modelBuilder.Entity<Organization>().ToTable("Organization").HasKey(x => x.OrgID);
modelBuilder.Entity<Patient>().ToTable("Patient").HasKey(x => x.PatientID);
modelBuilder.Entity<Program>().ToTable("Program").HasKey(p => p.ProgramId);
modelBuilder.Entity<Program>().ToTable("Program").Property(p => p.ProviderId).HasColumnName("ProvID");
modelBuilder.Entity<Program>()
.HasMany(p => p.Patients)
.WithMany(p => p.Programs)
.Map(pp =>
{
pp.MapLeftKey("ProgID");
pp.MapRightKey("PatientID");
pp.ToTable("PatProg");
});
modelBuilder.Entity<Organization>()
.HasMany(o => o.Programs)
.WithMany(p => p.Organization)
.Map(prov =>
{
prov.MapLeftKey("OrgID");
prov.MapRightKey("ProvID");
prov.ToTable("Provider");
});
现在,我想选择.Patient
Organization
return Context.Set<Organization>().AsNoTracking().Where(o => o.OrgID == organizationId)
.SelectMany(o => o.Programs)
.SelectMany(p => p.Patients)
但是,这会产生 0 回报。此外,当我在执行期间运行分析器时,输出查询与我映射的内容并不接近。
SELECT
[Join1].[PatientID1] AS [PatientID],
[Join1].[FirstName] AS [FirstName],
[Join1].[LastName] AS [LastName],
[Join1].[SSN#] AS [SSN#],
[Join1].[Suffix] AS [Suffix]
FROM
[dbo].[Provider] AS [Extent1]
INNER JOIN (
SELECT
[Extent2].[ProgID] AS [ProgID],
[Extent3].[PatientID] AS [PatientID1],
[Extent3].[FirstName] AS [FirstName],
[Extent3].[LastName] AS [LastName],
[Extent3].[SSN#] AS [SSN#],
[Extent3].[Suffix] AS [Suffix]
FROM
[dbo].[PatProg] AS [Extent2]
INNER JOIN [dbo].[Patient] AS [Extent3] ON [Extent2].[PatientID] = [Extent3].[PatientID] ) AS [Join1] ON [Extent1].[ProvID] = [Join1].[ProgID]
WHERE [Extent1].[OrgID] = 111
我真的不确定我在这里做错了什么。