A Party can have one or more Contact objects.
I want to select all Parties who's streetname contains a specific keyword.
If I just want to search in Party I can use the code below. But how do I extend it to also search in Contact?
public IQueryable<Party> SearchParties(List<string> keywords)
{
var predicate = PredicateBuilder.False<Party>();
foreach (string word in keywords)
{
var keyword = word;
predicate = predicate.Or(p => p.surname.Contains(keyword));
predicate = predicate.Or(p => p.lastname.Contains(keyword));
predicate = predicate.Or(p => p.number.Contains(keyword));
}
return db.Parties.Where(predicate);
}
Is there anything else you need to know?
EDIT
I guess I could create another predicate and then join them afterwards. Something like:
var predicate2 = PredicateBuilder.False<Contact>();
...and in the foreach:
predicate2 = predicate2.Or(p => p.streetname.Contains(keyword));
But how would I join predicate and predicate2 before returning?
EDIT2
Or, join the Party and Contact before doing the predicate Builder?
EDIT3
Here are parts of the generated classes:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Contact")]
public partial class Contact : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _id;
// ...more properties
private EntityRef<Party> _Party;
public Contact()
{
this._Party = default(EntityRef<Party>);
OnCreated();
}
}
The point is that you have multiple Contacts to a single Party, hence you should decide if you want to have a Party if "any of the Contacts match the street name" or "all of the Contacts match the street name".
For the first case it would be:
predicate = predicate.Or(p => p.Contacts.Any(c => c.streetname.Contains(keyword))));
This will work if your model has Contact as an associated object on the party object (and if it doesn't have a one-to-many relation)
predicate = predicate.Or(p => p.Contact.streetname.Contains(keyword));
来源:https://stackoverflow.com/questions/6328298/predicate-builder-with-two-tables