如何在左外连接Linq中使用Contains

时间:2017-09-13 13:07:21

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

我有这个查询

          from Room in PMSdb.Room_Tbl
                join Res in PMSdb.Reservation_Tbl on
                Room.Room_ID equals Res.Room_ID
                into ej
                from Res in ej.DefaultIfEmpty() 
                join Feature in PMSdb.Room_Features_Tbl on
                Room.Room_Features.Split(',').Contains(Feature.Room_Features_ID.ToString())
                into FE
                from Feature in FE.DefaultIfEmpty()
                  select new
                              {
                                  Room = Room.Room_Number,
                                  Room_type = RoomType.Room_Type_Code
                                  Feature =Feature.Feature_Name}

我需要这样做 Room.Room_Features.Split(',').Contains(Feature.Room_Features_ID.ToString())但它拒绝了 我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您应该真正考虑使用联结表对数据进行规范化,逗号分隔字段是数据库设计不良的标志。

话虽如此,问题在于实体框架无法将string.Split()转换为SQL查询。

如果您的数据存储为,val1,val2,,val3,(所以前缀并带有逗号后缀,逗号不是有效值),您可以使用string.Contains,其中可以转换为SQL:

Room.Room_Features.Contains($",{Feature.Room_Features_ID},")

答案 1 :(得分:-2)

这个怎么样:

(from Room in PMSdb.Room_Tbl
            join Res in PMSdb.Reservation_Tbl on
            Room.Room_ID equals Res.Room_ID
            into ej
            from Res in ej.DefaultIfEmpty()
            select new { room = Room, res = Res)
            .Where(x => x.Res == null)
            .Select(x => new {
                             Room = x.room.Room_Number,
                             Room_type = x.room.Room_Type_Code,
                             Features = x.room.Room_Features.Split(new char[] {','})
                                .Select(y => PMSdb.Room_Features_Tbl.Where(z => z.Room_Features_ID.ToString() == y.Trim()).FirstOrDefault())
                                .ToList() 
            }).ToList();