2009-09-26 93 views
6

我使用的通用存储库模式与方法:实体框架和存储库模式问题

private ObjectQuery<T> ObjectQueryList() 
    { 
     var list = CamelTrapEntities.CreateQuery<T>(EntitySetName); 
     return list; 
    } 

public IQueryable<T> List() 
    { 
     return ObjectQueryList(); 
    } 

梅托德列表()返回的IQueryable <牛逼>,becase的IQueryable的<牛逼>容易嘲笑。我也有扩展方法:

public static IQueryable<T> Include<T>(this IQueryable<T> obj, string path) 
    { 
     if (obj is ObjectQuery<T>) 
      (obj as ObjectQuery<T>).Include(path); 

     return obj; 
    } 

此方法用于存储库之外获得与已加载,例如导航属性实体列表:List.Include(“CreatedBy”)。问题是它不起作用。所有包含都被忽略。当我改变列表()方法来

public ObjectQuery<T> List() 
    { 
     return ObjectQueryList(); 
    } 

一切工作正常。

我应该如何实现存储库模式才能执行更复杂的查询?

回答

6

反射给了我一个答案:

public ObjectQuery<T> Include(string path) 
{ 
    EntityUtil.CheckStringArgument(path, "path"); 
    return new ObjectQuery<T>(base.QueryState.Include<T>((ObjectQuery<T>) this, path)); 
} 

包括返回新的ObjectQuery对象和我的include函数返回旧的对象。更改为

public static IQueryable<T> Include<T>(this IQueryable<T> obj, string path) 
{ 
    if (obj is ObjectQuery<T>) 
     return (obj as ObjectQuery<T>).Include(path); 

    return obj; 
} 

解决了这个问题。几个小时输了,我讨厌实体框架更多:)

它使我也意识到,我应该创建另一个带有Include参数的List函数,并且不允许包含外部存储库。

1

Here是我见过的EF中最全面的Repository模式实现。我不能确定它是否会允许你执行Include(),但是如果我阅读它应该执行的权利。

1

用的EntityFramework 4.1,DbExtensions(System.Data.Entity.DbExtensions)解决了这一问题,并且增加了本身既.Include([string path]).Include([property expression])任何IQueryable<T>

只要确保使用存储库的项目引用了EntityFramework,并且与任何扩展方法一样,在类文件中指定using System.Data.Entity;即可访问这些扩展。