2009-11-07 63 views
2

我使用这个方法有麻烦:问题使用排序依据与实体框架和ObjectContext.CreateQuery(T)

public ObjectQuery<E> DoQuery(string columnName, int maximumRows, int startRowIndex) 
{ 
    var result = (ObjectQuery<E>)_ctx.CreateQuery<E> 
    ("[" + typeof(E).Name + "]").OrderBy(/*???*/).Skip<E>(startRowIndex).Take(maximumRows); 

    return result; 
} 

我不知道有什么需要在OrderBy节去。我试过把.OrderBy遗漏掉,但最终给我一个错误,说它需要排序,这样我才能取一定数量的行。

我想按ID字段排序。在一种情况下,我将实体名称作为行,此实体的ID被命名为RowID

有谁知道我可以通过ID字段命令?

注意:这是一个使用实体框架的通用存储库。传入的columnName是我想要排序的列,但它可能只是ID字段的名称。

回答

3

当我创建我的存储库时,我认为每个EntityObject都有ID属性。然后,我创建库:

public class Repository<T> : IRepository<T> where T : EntityObject, IBasicEntityInfo 

IBasicEntityInfo:

public interface IBasicEntityInfo 
{ 
    int ID { get; set; } 
} 

然后

OrderBy(a => a.ID) 

自动生成EntityObject类没有实现IBasicEntityInfo接口,但我用T4生成:

public partial class User : IBasicEntityInfo ,ILastModificationInfo 
public partial class Project : IBasicEntityInfo ,ILastModificationInfo 
public partial class Group : IBasicEntityInfo ,ILastModificationInfo 
public partial class GroupUser : IBasicEntityInfo 
public partial class OperationSystem : IBasicEntityInfo ,ILastModificationInfo 

T4很简单:

<#@ template language="C#" #> 
<#@ output extension="cs" #> 
<#@ import namespace="System.Collections.Generic" #> 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Web; 

<# 
    String[] classNames = new String[] {"User","Project","Group","GroupUser","OperationSystem","TaskType","Priority","Severity","Status","Version","Platform","Task","TaskUser","Attachment","Comment","Setting"}; 
#> 
namespace CamelTrap.Models 
{ 
<# foreach(String className in classNames) { #> 
    public partial class <#= className #> : IBasicEntityInfo 
    { 
    } 
<# } #> 
} 

进行这样的假设解决其他问题也是一样,从创建复杂的表达式救了我。

+1

这在很多方面都很有用(我们几乎完成同样的事情),但实际上并没有帮助解决他遇到的问题。 – 2009-11-09 13:36:01

+0

它确实解决了这个问题,因为你可以使用OrderBy(a => a.ID)。我的存储库通过实现IBasicEntityInfo知道每个对象都具有ID属性。 – LukLed 2009-11-09 14:36:27

+0

当然,你的解决方案稍微简单:) – LukLed 2009-11-09 14:37:31

4

你只是做:

.OrderBy("it.Id") 

...意味着你的ID字段被称为 “ID”。在查询生成器中,“it”表示实体。请参阅this page以供参考。