简体   繁体   English

使用Linq Lambda按字符串子对象属性过滤实体对象列表

[英]Filter list of entity objects by string child object property using Linq Lambda

I am trying to return an IQueryable lands filtered by a child object property Owner.Name. 我正在尝试返回由子对象属性Owner.Name过滤的IQueryable土地。 Is working well with the query style solution, but I want to use a lambda one. 与查询样式解决方案配合良好,但我想使用lambda。

On short these are my classes mapped by EntityFramework: 简而言之,这些是我由EntityFramework映射的类:

public class Land
{
     public int Id { get; set; }

     public virtual ICollection<Owner> Owners { get; set; }
}

public class Owner
{
        public int Id { get; set; }
        public string Name { get; set; }
        public int LandId { get; set; }

        public virtual Land Lands { get; set; }
}

The query which is working fine: 工作正常的查询:

 var list = from land in db.Lands
                   join owner in db.Owners on land.Id equals Owner.LandId
                   where owner.Name.Contains("Smit")
                   select land;

I was trying using this: 我正在尝试使用此:

var list = db.Lands.Where(lnd => lnd.Owners.Count() > 0 &&
             lnd.Owners.Where(own => own.Name.Contains("Smit")).Count() > 0);

It works only for small lists, but for some with thousands of records it gives timeout. 它仅适用于小型列表,但对于具有数千条记录的某些列表,它会给出超时。

Well, one issue which may be causing the speed problem is that your lambda version and your non-lambda versions do very different things. 嗯,可能导致速度问题的一个问题是您的lambda版本和非lambda版本做的事情大不相同。 You're non lambda is doing a join with a where on one side of the join. 您不是lambda,正在使用联接一侧的where进行联接。

Why not just write the lambda equivalent of it? 为什么不只写等效的lambda?

var list = db.Lands.Join(db.Owners.Where(x=> x.Name.Contains("Smit")), a=> a.Id, b => b.LandId, (a,b) => a).toList();

I mean, that is the more direct equivalent of your non lambda 我的意思是,这比您的非lambda更直接

我认为您可以使用以下一种:

var list = db.Lands.Where(lnd => lnd.Owners.Any(x => x.Name.Contains("Smit")));

Try something more straightforward: 尝试一些更简单的方法:

var lands = db.Owners.Where(o => o.Name.Contains("Smit")).Select(o => o.Lands);

You just need to make sure that Owner.Name is not null and LINQ will do the rest. 您只需要确保Owner.Name不为null,其余的将由LINQ完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM