Skip to main content
 首页 » 编程设计

c#之编写谓词以使用 Entity Framework 搜索存储库时出现问题(相当于在 SQL 中使用 Join)

2024年02月23日18虾米哥

我们正在使用代码优先 Entity Framework 4.1 来持久化数据。我们的一些实体有这样的关系:

[Serializable] 
public class Conference 
{ 
    private IList<Attendee> people; 
    private string name;         
 
    public IList<Attendee> People 
    { 
        get { return this.team; } 
        private set { this.team = value; } 
    } 
 
    public string Name 
    { 
        get { return this.name; } 
        private set { this.name = value; } 
    } 
} 
 
[Serializable] 
public class Attendee 
{ 
    private string firstname; 
    private string surname; 
 
    public string Firstname 
    { 
        get { return this.firstname; } 
        private set { this.firstname = value; } 
    } 
 
    public string Surname 
    { 
        get { return this.surname; } 
        private set { this.surname = value; } 
    } 
} 

我想使用 LINQ 查询我们的 session 存储库。我可以使用如下搜索规范按名称轻松找到 session :

public class ConferenceNameSearch : ISpecification<Conference> 
{ 
    public Expression<Func<Conference, bool>> IsSatisfied() 
    { 
        return a => a.Name == "Christmas Party"; 
    } 
} 

但是我在编写一个搜索规范时遇到了真正的麻烦,该规范将返回至少有 1 个名字为“David”的人参加的所有 session :

public class ConferenceAttendeeNameSearch : ISpecification<Conference> 
{ 
    public Expression<Func<Conference, bool>> IsSatisfied() 
    { 
        return a => a.People.Contains( ???? err "David"; 
    } 
} 

有没有办法做到这一点?此外,如果不只是搜索与会者名为“David”的 session ,我有一个我想要匹配的 List 名称,那么将它的复杂性提高 1 级,这也可能吗?

感谢您的帮助!

请您参考如下方法:

看起来你想要 IEnumerable<T>.Any :

public class ConferenceAttendeeNameSearch : ISpecification<Conference> 
{ 
    public Expression<Func<Conference, bool>> IsSatisfied() 
    { 
        return a => a.People.Any(p => p.FirstName.Equals("David")); 
    } 
} 

Any返回一个 bool 值,指示序列的任何元素是否与条件匹配。您可以将其行为描述为类似于 sequence.Where(condition).Count() > 0 .

您应该了解的一个相关方法(虽然它不适用于此处)是 IEnumerable<T>.All .