C# 如何使用标识列表从实体框架获取ObjectResult

C# 如何使用标识列表从实体框架获取ObjectResult,c#,entity-framework,C#,Entity Framework,我有一组标识值,需要用作从实体框架返回ObjectResult的查询值 以下是哈希集: HashSet<int> officeIds = new HashSet<int>(); HashSet-officeIds=new-HashSet(); 以下是我尝试或多或少运行的查询: ObjectResult<FilingOffice> offices = ctx.FilingOffice.Where(office => office IN officeId

我有一组标识值,需要用作从实体框架返回ObjectResult的查询值

以下是哈希集:

HashSet<int> officeIds = new HashSet<int>();
HashSet-officeIds=new-HashSet();
以下是我尝试或多或少运行的查询:

ObjectResult<FilingOffice> offices = ctx.FilingOffice.Where(office => office IN officeIds.ToList());
ObjectResult offices=ctx.FilingOffice.Where(office=>officein-officeid.ToList());
上面的“office=>officein-officeIds.ToList()”部分是我无法使用的,而且在web上还没有找到任何用于在给定主键列表的情况下检索对象的示例


ctx是System.Data.Objects.ObjectContext,我目前没有任何方法来检查它,但看起来您正在尝试查看office对象本身是否在列表中,您可能想检查其ID是否在您拥有的ID列表中,如

ObjectResult<FilingOffice> offices = ctx.FilingOffice.Where(office => office.Id IN officeIds.ToList());
ObjectResult offices=ctx.FilingOffice.Where(officeid.ToList()中的office=>office.Id);
如果这不起作用,那么运行代码时的一些指示将很有帮助。

尝试以下操作

var offices = ctx.FilingOffice.Where(o => officeIds.ToList().Contains(o.Id));

但我不能绝对确定实体框架是否支持此查询-我倾向于认为您必须将
officeid.ToList()
存储在局部变量中。

其他人给出的示例在实体框架中不起作用,因为您不能在LINQ 2实体中混合使用客户端和服务器端枚举

相反,您需要手动构建OR表达式

我运行了一系列的,并向您展示了如何构建OR表达式

希望这有帮助


Alex

有一种替代方法可以绕过LINQ到实体的限制。 您可以使用支持IN子句的实体SQL

string entitySql=string.Format(“在{{{0}}}中选择FilingOffice中的值O作为O,其中O.Id,{{0}}”,string.Join(“,”,officeId.ToList().ConvertAll(officeId=>officeId.ToString()).ToArray())

ObjectQuery办公室=新的ObjectQuery(entitySql,ctx)

我有类似的问题,我通过内部连接解决了这个问题。请参阅下面我的函数

public IEnumerable<AccountsCache> GetAccountsById(IEnumerable<int> accountIds)
{
    var query =
        from regAccount in registeredAccounts
        join Ids in accountIds on regAccount.AccountId equals Ids
        select regAccount;
    return query;
}
public IEnumerable GetAccountsById(IEnumerable AccountId)
{
变量查询=
来自registeredAccounts中的ReAccount
将ID加入ReAccount上的AccountId中。AccountId等于ID
选择重新记帐;
返回查询;
}
在你的环境中

HashSet<int> officeIds = new HashSet<int>();

ObjectResult<FilingOffice> offices = 
    from f in ctx.FilingOffice
    join Ids in officeIds on f.officeId equals Ids
select f;
HashSet-officeIds=new-HashSet();
ObjectResult办公室=
来自ctx.FilingOffice中的f
在f上的officeId中加入ID。officeId等于ID
选择f;

我有过很多类似的问题,另一个堆栈溢出问题是:

我更喜欢使用:

var entities = db.Entities.WhereIn(x => x.Id, ids);

代码没有正确输出:public IEnumerable GetAccountsById(IEnumerable AccountId){var query=from registeredAccount中的ReAccount将ID加入ReAccountId中。AccountId=Ids选择ReAccount;返回query;}//并且您的实现HashSet OfficeId=new HashSet();ObjectResult offices=from ctx中的f.FilingOffice在f上的officeId中加入ID.officeId=Ids选择f;