简体   繁体   中英

Linq to EF Dynamic Search with multiple properties

Given the follwing:

SQL Tables:

Names
-----
Id (int)
FirstName (varchar)
LastName (varchar)

NameProperties
----------
Id (int)
NameId (int) FK to Names Id
PropType (int)
PropValue (int)

Every Name can have multiple NameProperties

Now my searchCriteria Class is as follows

public string FirstName { get; set; }
public string LastName { get; set; }
public List<KeyValuePair<int,int>> Properties { get; set; } Corresponding to a list of PropType ProValue

How do I search using linq to EF when having multiple PropType & PropValues ?

Supposing that the criteria in Properties should all be met (ie AND and not OR ) you could do this:

// c is a searchCriteria object.
var query = context.Names
    .Where(n => n.FirstName == c.FirstName && n.LastName == c.LastName);
foreach(var pair in c.Properties)
{
    query = query.Where(n => n.NameProperties.Any(np => 
        np.PropType == pair.PropType && np.PropValue == pair.PropValue;
}

(not checked for syntax, just showing the idea).

It is not very efficient to query this way, but querying an Entity–attribute–value model is always a pain. If it is even remotely possible to change the Name table in a way that it includes columns corresponding with the NameProperties then do it.

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