本文介绍了带有两个表的谓词生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

缔约方可以有一个或多个 Contact 对象.

A Party can have one or more Contact objects.

我想选择街道名称包含特定关键字的所有缔约方.
如果我只想在聚会中进行搜索,则可以使用下面的代码.但是,如何将其扩展为也可以在 Contact 中进行搜索?

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

...并在foreach中:

...and in the foreach:

predicate2 = predicate2.Or(p => p.streetname.Contains(keyword));

但是在返回之前,我将如何加入谓词和谓词2?

But how would I join predicate and predicate2 before returning?

EDIT2
还是在进行谓词构建器之前加入 Party Contact ?

EDIT2
Or, join the Party and Contact before doing the predicate Builder?

EDIT3
这是生成的类的一部分:

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".

第一种情况是:

predicate = predicate.Or(p => p.Contacts.Any(c => c.streetname.Contains(keyword))));

这篇关于带有两个表的谓词生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:16