Linq to Entities many to many select query

后端 未结 4 1378
独厮守ぢ
独厮守ぢ 2020-12-29 06:39

I am at a loss with the following query, which is peanuts in plain T-SQL.

We have three physical tables:

  • Band (PK=BandId)
  • MusicStyle (PK=Muic
4条回答
  •  执念已碎
    2020-12-29 07:13

    from ms in Context.MusicStyles
    where ms.Bands.Any(b => b.Name.Contains(search))
    select ms;
    

    This just returns the style, which is what your question asks for. Your sample SQL, on the other hand, returns the style and the bands. For that, I'd do:

    from b in Context.Bands
    where b.Name.Contains(search)
    group b by band.MusicStyle into g
    select new {
        Style = g.Key,
        Bands = g
    }
    
    from b in Context.Bands
    where b.Name.Contains(search)
    select new {
        BandName = b.Name,
        MusicStyleId = b.MusicStyle.Id,
        MusicStyleName = b.MusicStyle.Name,
        // etc.
    }
    

提交回复
热议问题