2

我有很多Accounts,每个帐户也可以有子帐户。因此,我知道一个帐户是否为root的方式归功于ParentId属性中的值。
所以,事实证明,我的代码有这样的东西在很多地方:.Where(acc => acc.ParentId == 0)所以我认为有关创建看起来像这样的属性:简化此属性以用于谓词

public bool IsRootAccount 
{ 
    return a.ParentId == 0; 
} 

看来工作,它编译,但在运行时我得到但以下情况除外:

Load operation failed for query 'GetAccounts'. The specified type member 'IsRootAccount' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

有一个简单的方法可以让我实现我想要什么?

我也想过创造一些东西,会返回一个没有运气的Expression<Func<Account, bool>>

编辑:我为IsRootAccount财产尝试是为了使用这样的.Where(acc => acc.IsRootAccount)

+2

“IsRootAccount”的返回类型与返回的值('bool'!= lambda)不匹配。 – 2012-03-09 00:17:51

+0

谢谢,我解决了它...我从一个不同的属性复制:) – sebagomez 2012-03-09 00:26:14

+0

你也可以告诉我们你试图建立的查询消耗这个属性?我怀疑你可以做到你想要的东西,但我们可能会提出一些替代解决方案。 – 2012-03-09 00:31:49

回答

1

提供此功能的一种非常简单的方法是使用扩展方法。

尝试这样:

public static class AccountEx 
{ 
    public static IQueryable<Account> WhereIsRootAccount(
      this IQueryable<Account> source) 
    { 
     return source.Where(acc => acc.ParentId == 0); 
    } 
} 

然后,您将与.WhereIsRootAccount()取代.Where(acc => acc.ParentId == 0)每次使用。

这种方法的优点是它与EF一起工作,并且它提供了一种查询您的根帐户的流利方式。如果您需要修改根帐户的定义,则您也只有一个地方可以进行更改。并且它不会污染您的Account类,并且不必要的代码。

我希望这会有所帮助。


基于您的评论,试试这个:

public static class AccountEx 
{ 
    public static EntityQuery<Account> WhereIsRootAccount(
      this EntityQuery<Account> source) 
    { 
     return source.Where(acc => acc.ParentId == 0); 
    } 
} 

由于WhereEntityQuery<>支持,那么它应该仍然正常工作。

+0

RIA服务的方法,我喜欢这个主意......会试试看 – sebagomez 2012-03-09 12:03:47

+0

它帮助,谢谢...但它不能从使用Silverlight客户端,对吗?在客户端有没有办法做到这一点? – sebagomez 2012-03-09 12:12:14

+0

@sebastian - 我对Silverlight并不完全熟悉 - 你能告诉我为什么你不认为Silverlight能起作用吗? – Enigmativity 2012-03-09 12:25:34

0

这里的东西,我发现,但我想看看是否有事情好做。
我知道EF不知道如何将我的谓词转换为SQL,因为我的属性。 所以我不能做到这一点:

Context.Load(Context.GetAccountsQuery().Where(acc => acc.IsRootAccount), ParentAccountsArrived, null); 

但我可以用我的财产,一旦过滤的结果回来从服务器:

public void LoadParentAccounts() 
{ 
    Context.Load(Context.GetAccountsQuery(), ParentAccountsArrived, null); 
} 
void ParentAccountsArrived(LoadOperation<Account> lo) 
{ 
    foreach (var account in lo.Entities.Where(acc => acc.IsRootAccount)) 
    { 
     ParentAccounts.Add(account.Name); 
    } 
} 

这是要走的路?这种改变是否存在性能问题?

+0

是什么GetAccountsQuery – Nix 2012-03-09 00:53:51

+0

是它返回一个IQueryable的''一个 – sebagomez 2012-03-09 00:56:19