LINQ内部多对多查询选择

时间:2019-03-14 14:19:28

标签: c# sql-server linq many-to-many

enter image description here

这是我尝试进行多对多linq请求的尝试,但是它没有按预期工作。 CVVM类具有属性ICollection<FormationVM> Formations

var cv = (
    from c in context.CVs
    where c.Id == id
    select new CVVM
    {

        Id = id,    
        Formations = 
           from f in context.Formations
           from c2 in context.CVs
           where c2.Id == id 
           select new FormationVM
           {
               Id = form.Id,
               DateDebut = form.DateDebut,
               DateFin = form.DateFin,
               Ecole = form.Ecole,
               Description = form.Description,
               Diplome = form.Diplome
           }
    }).FirstOrDefault();

为什么Model.Formations.Count()在我的视图中返回3而不是2?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。这段代码有效:

using (Context context = new Context())
                {

                    var cv =
                                    (
                                        from c in context.CVs
                                        where c.Id == id && c.PersonneId == userId
                                        select new CVVM
                                        {
                                            Titre = c.Titre,
                                            MontrerPhoto = c.MontrerPhoto,
                                            Layout = c.Layout,
                                            Id = id,
                                            FormAction = "EditionTraitement",
                                            FormTitre = "Edition de ce CV",

                                             Formations = from form in c.Formations
                                                          where c.Id == id && c.PersonneId == userId
                                                          select new FormationVM
                                                         {
                                                             Id = form.Id,
                                                             DateDebut = form.DateDebut,
                                                             DateFin = form.DateFin,
                                                             Ecole = form.Ecole,
                                                             Description = form.Description,
                                                             Diplome = form.Diplome
                                                         }

                                        }).FirstOrDefault();

}