predicate builder with two tables

家住魔仙堡 提交于 2020-01-13 05:13:07

问题


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

回答1:


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



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!