predicate builder with two tables

2019-04-12 20:46发布

enter image description here

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();
    }
}

2条回答
在下西门庆
2楼-- · 2019-04-12 21:00

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))));
查看更多
仙女界的扛把子
3楼-- · 2019-04-12 21:17

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));
查看更多
登录 后发表回答