C# 简单查询性能
假设我有4张表A、B、C和D 让B列表进入下拉列表的最佳方式是什么。 条件是每个记录都应该有相关的D1列表 因此,如果B没有D1记录,我不应该在下拉列表中显示它 D1是D的子类 我是如何做到的:C# 简单查询性能,c#,entity-framework,linq,C#,Entity Framework,Linq,假设我有4张表A、B、C和D 让B列表进入下拉列表的最佳方式是什么。 条件是每个记录都应该有相关的D1列表 因此,如果B没有D1记录,我不应该在下拉列表中显示它 D1是D的子类 我是如何做到的: // number 2 to specify the selected A Table normally it's a variable var b_Per_A = Uow.B.GetAll().Where(x => x.A_Id == 2).ToList(); var b_list = new
// number 2 to specify the selected A Table normally it's a variable
var b_Per_A = Uow.B.GetAll().Where(x => x.A_Id == 2).ToList();
var b_list = new List<B>();
foreach (var b in b_list)
{
var d =
Uow.D1.GetAll().Where(x => x.C.B_Id == b.Id);
if (!d.IsNullOrEmpty()) // extension method that checks if a collection is null or empty
{
b_list.Add(b);
}
}
更新2:
我的模型是
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<B> ChildBs { get; set; }
}
public class B
{
public int Id { get; set; }
public string Name { get; set; }
public A ParentA { get; set; }
public IEnumerable<C> ChildCs { get; set; }
}
public class C
{
public int Id { get; set; }
public string Name { get; set; }
public B ParentB { get; set; }
public IEnumerable<D> ChildDs { get; set; }
}
public class D
{
public int Id { get; set; }
public string Name { get; set; }
public C ParentC { get; set; }
}
public class D1 : D
{
/// other properties
}
公共A类
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共IEnumerable ChildBs{get;set;}
}
公共B级
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共A ParentA{get;set;}
公共IEnumerable ChildCs{get;set;}
}
公共C类
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共B ParentB{get;set;}
公共IEnumerable childs{get;set;}
}
D类公共服务
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共C ParentC{get;set;}
}
公开课D1:D
{
///其他属性
}
将变量d=Uow.d.GetAll()放在其中(x=>x.C.B_Id==B.Id);在你的房间之外。我还建议您使用IEnumerable/ICollection而不是List,并使用for循环而不是foreach。索引循环更快。鉴于您已确认在实体类上具有导航属性,这可以通过单个表达式实现:
var result = Uow.B.GetAll()
.Where(b =>
b.ParentA.Id == 2 &&
b.ChildCs.Any() &&
b.ChildCs.SelectMany(c => c.ChildDs).Any())
.ToList();
这将把过滤推送到数据库中,而不是在内存中进行过滤,应该会更有效
另外,我假设父导航属性永远不会为null
,并且子集合总是初始化的
为什么不使用存储过程而不是linq?实体对象上有导航属性吗?也就是说,
C.childs
和D.ParentC
不要使用GetAll()
然后过滤它。直接过滤它,否则,如果您有1000条记录,它将获得所有1000条记录,然后您尝试过滤,这将影响某些性能。@如果GetAll()
返回一个IQueryable
@ChrisPickford是,我有导航属性,如果您将其置于循环之外,他将如何使用它来检查b.id
?需要更多的解释谢谢你的回答,我会尝试一下,只是父/子术语很混乱,因为没有继承。@Maro如果你在问题中添加实体模型定义,我会更新答案以匹配你的属性名称。你的代码运行良好,我得到了所有结果,但是我犯了一个错误,忘了提到类D是一种抽象类,我正在寻找它的一个children,比如说D1。如果你有一个解决方案,那就太好了,否则我会拒绝你的答案,因为我忘记了是错误的。我会更新我的问题好的,我会尝试复制你的模型并修改它
var result = Uow.B.GetAll()
.Where(b =>
b.ParentA.Id == 2 &&
b.ChildCs.Any() &&
b.ChildCs.SelectMany(c => c.ChildDs).Any())
.ToList();