将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 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);
}
}
虽然有效,但速度很慢
更新:
GetAll()
的签名是
IQueryable<T> GetAll();
更新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
}
答案 0 :(得分:1)
鉴于您已确认您的实体类具有导航属性,可以在单个表达式中实现:
var result = Uow.B.GetAll()
.Where(b =>
b.ParentA.Id == 2 &&
b.ChildCs.Any() &&
b.ChildCs.SelectMany(c => c.ChildDs).Any())
.ToList();
这会将过滤推送到您的数据库而不是在内存中进行,并且效率会更高。
另外,我假设父导航属性永远不会是null
,并且子集合总是被初始化。
答案 1 :(得分:-3)
把你的 var d = Uow.D.GetAll()。在你的foreach之外的地方(x =&gt; x.C.B_Id == b.Id); 。我还建议你使用IEnumerable / ICollection而不是List并使用for循环代替foreach。索引循环更快。