简体   繁体   中英

c# entity framework mixing linq to objects with linq to entities

I have database which values that I want to search.

To search something, user needs to select specific checkboxes which value is contained in list in memory (otherwise any change value of checkbox would result saving database, what I want to avoid).

Data from my database are loaded by

.Load()

method.

So, my problem is that idk how to construct query which mix my database values with memory true/false values.

var query1 = from i in db.MyValuesTable
              from j in MyMemoryObjects
              where j.IsTrue && j.Id == i.Tab2Id && i.Value.Contains(_searchPhrase)
              select i;

(from i in db.TableToLoad
from j in query1
where i.CollectionWithValues.Any(x => x.Tab1Id == j.Tab1Id && x.Tab2Id == j.Tab2Id).select i).Load();

My queries may be a bit confusing, so I'll put database schemes below (EF Code First)

//db object
public class MyValuesTable
{
   public int Tab1Id { get; set; }
   public int Tab2Id { get; set; }
   public string Value { get; set; }
}

//memory object
public class MyMemoryObjects
{
   public int Id { get; set; }
   public bool IsTrue { get; set; }
}

//db object
public class TableToLoad
{
   public int Tab1Id { get; set; }
   public int Tab2Id { get; set; }
   public string Value { get; set; }
}

Mixing LINQ to Entities with LINQ to Objects is not generally supported. Practically the only supported construct is Contains method applied on in memory primitive type IEnumerable<T> , which translates to SQL IN (value1, value2, ...) clause.

Luckily it's applicable to your scenario since the j.IsTrue && j.Id == i.Tab2Id criteria can be converted to in memory list of j.Id with j.IsTrue filter applied, which then can be used inside the LINQ to Entities query as Contains criteria:

// has to be variable outside of the L2E query
var idFilter = from j in MyMemoryObjects
               where j.IsTrue
               select j.Id;

var query1 = from i in db.MyValuesTable
             where idFilter.Contains(i.Tab2Id) // <-- and use it inside
                 && i.Value.Contains(_searchPhrase)
             select i;

// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM