使用实体框架将表连接到列表

时间:2018-07-09 01:26:48

标签: c# entity-framework

我有以下Entity Framework函数,它将表连接到列表。 serviceSuburbList中的每个项目都包含两个整数ServiceIdSuburbId

public List<SearchResults> GetSearchResultsList(List<ServiceSuburbPair> serviceSuburbList)
{
    var srtList = new List<SearchResults>();
    srtList = DataContext.Set<SearchResults>()
                         .AsEnumerable()
                         .Where(x => serviceSuburbList.Any(m => m.ServiceId == x.ServiceId && 
                                                                m.SuburbId == x.SuburbId))
                         .ToList();

    return srtList;
}

很明显,AsEnumerable破坏了我的表现。我不确定执行此操作的另一种方法。基本上,我有SearchResults表,我想查找与serviceSuburbList匹配的记录。

1 个答案:

答案 0 :(得分:0)

如果serviceSuburbList的长度不大,则可以创建多个Union

var table = DataContext.Set<SearchResults>();
IQuerable<SearchResults> query = null;
foreach(var y in serviceSuburbList)
{
    var temp = table.Where(x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId);
    query = query == null ? temp : query.Union(temp);
}

var srtList = query.ToList();

另一种解决方案-使用Z.EntityFramework.Plus.EF6库:

var srtList = serviceSuburbList.Select(y => 
                 ctx.Customer.DeferredFirstOrDefault(
                    x => x.ServiceId == y.ServiceId && x.SuburbId == y.SuburbId
                 ).FutureValue()
              ).ToList().Select(x => x.Value).Where(x => x != null).ToList();
//all queries together as a batch will be sent to database 
//when first time .Value property will be requested