如何使用Linq to Entity查询来搜索多对多关系

时间:2018-03-28 01:42:27

标签: c# linq-to-entities

我有一个包含3个表的Sql Server数据库:

第一个名为“Drugs”的表有字段:“DrugID”,“Name”

第二个名为“Ingredients:has fields”的表名为IngredientID“,”Name“

第3个表表示其他2个表之间的多对多关系,并且具有“DrugID”,“IngredientID”,“Concentration”字段

假设我在名为“DrugA”的“药物”表中有一种药物,与“成分”表中的3种成分有多对多的关系

实体查询中搜索与((全部))相同成分的所有其他药物的最佳linq是什么

1 个答案:

答案 0 :(得分:1)

这并不容易。我通过创建相对类和列表来模拟您的数据库场景。我跑了并测试了这段代码。

实施后将返回所有DrugId,其中有常见成分作为药物,名称为" Drug1"。

<强>类

public class Drug
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Ing
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Relation
{
    public int DId { get; set; }
    public int IId { get; set; }
}

LINQ实施

List<Drug> drugs = new List<Drug>();
List<Ing> ings = new List<Ing>();
List<Relation> rel = new List<Relation>();

for (int i = 1; i <= 3; i++)
{
    drugs.Add(new Drug() { Id = i, Name = "Drug" + i });
    ings.Add(new Ing() { Id = i, Name = "Ing" + i });
}

rel.Add(new Relation() { DId = 1, IId = 1 });
rel.Add(new Relation() { DId = 1, IId = 2 });
rel.Add(new Relation() { DId = 1, IId = 3 });
rel.Add(new Relation() { DId = 2, IId = 1 });
rel.Add(new Relation() { DId = 2, IId = 2 });
rel.Add(new Relation() { DId = 3, IId = 2 });
rel.Add(new Relation() { DId = 3, IId = 3 });
rel.Add(new Relation() { DId = 3, IId = 1 });


var ingredients = rel
        .Join(drugs, r => r.DId, d => d.Id, (r, d) => new { r, d })
        .Where(rdi => rdi.d.Name == "Drug1")
        .Select(m => m.r.IId).OrderBy(m => m).ToList();

var drugIds = rel.GroupBy(r => r.DId, (key, g) => new { D = key, I = g.Select(a => a.IId).OrderBy(a => a).ToList() })
        .Where(di => Enumerable.SequenceEqual(di.I, ingredients))
        .Select(s => s.D).ToList();