LINQ查询多对多senf-reference表

时间:2017-03-03 11:14:55

标签: c# entity-framework linq linq-to-entities

我有2个EF模型:

    public class Medicament
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Required]
    public string InternationalName { get; set; }

    public ICollection<MedicamentMedicaments> MedicamentMedicamentses { get; set; }
}

public class MedicamentMedicaments
{
    [Key]
    [Column(Order = 0)]
    public Guid MedicamentId { get; set; }

    [Key]
    [Column(Order = 1)]
    public Guid AnalogId { get; set; }

    public Medicament Medicament { get; set; }
    public Medicament Analog { get; set; }
}

例如MedicamentMedicaments内容:

  • | MedicamentId | AnalogId |
  • | 1 | 5 |
  • | 5 | 3 |

我想通过药物ID和LINQ查询接收药物类似物?

2 个答案:

答案 0 :(得分:0)

List<Analog> result = yourDbContext.MedicamentMedicaments.Where(t => t.MedicamentId == yourMedicamentId).Select(t => t.Analog).ToList()

 List<Analog> result = yourDbContext.Medicament.SelectMany(t => t.MedicamentMedicamentses).Where(t => t.MedicamentId == yourMedicamentId).Select(t => t.Analog).ToList()

 List<Analog> result = yourDbContext.Medicament.Where(t => t.Id == yourMedicamentId).SelectMany(t => t.MedicamentMedicamentses).Select(t => t.Analog).ToList()

答案 1 :(得分:0)

我找到了解决方案:

var query = from medicament in Db.Medicaments
            where medicament.Id == medId
            from mm in Db.MedicamentMedicamentses
            where medicament.Id == mm.MedicamentId || medicament.Id == mm.AnalogId
            select medicament.Id == mm.MedicamentId ? mm.Analog : mm.Medicament;