2013-06-20 21 views
0

我有以下幾點:如何擴展EF儲存庫模型以執行更復雜的查詢?

public partial class Subject 
{ 
    public Subject() 
    { 
     this.Contents = new List<Content>(); 
    } 
    public int SubjectId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Content> Contents { get; set; } 
} 

public partial class Content 
{ 
    public int ContentId { get; set; } 
    public int ContentTypeId { get; set; } 
    public string Title { get; set; } 
    public string Text { get; set; } 

    public int SubjectId { get; set; } 
    public virtual Subject Subject { get; set; } 
} 

在我的SQL Server數據庫中,我有SubectId和ContentTypeId

的內容表中的索引

我班正在尋找與具有這樣的方法,例如標準庫然而,使用存儲庫模型GetAll()和GetId(id)有一種方法可以執行更復雜的查詢。在這種情況下,我會以某種方式想要查詢特定的SujectId和contentTypeId。我想要避免的是查詢獲取每個內容記錄,然後篩選出我需要的內容。我想以某種方式發送一個真正的查詢,確切地說我需要SQL Server。

目前我通用倉庫有以下幾點:

public virtual T GetById(int id) 
    { 
     return DbSet.Find(id); 
    } 

我能做什麼,我需要通過實施創建ContentRepository並具有類似如下:如果是的話我怎麼會

public IQuerable<Content> GetAllBySubjectId(int id) 
    { 
     return DbSet.Where(c => c.SubjectId == id); 
    } 

使用GetAllBySubjectId並在檢查ContentId ==「01」的地方添加例如?

+2

[Linq to Entities](http://msdn.microsoft.com/en-us/library/bb386964.aspx)的使用將導致發送實際查詢數據庫。 – tpeczek

回答

1

你可以添加到您的存儲庫的方法是這樣的:

public IQueryable<T> Find(Expression<Func<T, bool>> predicate) 
{ 
    return DbSet.Where<T>(predicate); 
} 

然後寫某事像:

repository.Find(c => c.SubjectId == myId); 
+0

非常感謝。我還有一個關於如何將服務層置於其間的問題,但現在我會將其標記爲已接受,然後將其作爲另一個問題提出。 – Alan2

0

如果您使用實體框架與LINQ,它會嘗試生成併發送優化查詢數據庫,例如,如果你做類似的事情:

var contents = 
    from c in Context.Contents // or directly the DbSet of Contents 
    where c.ContentTypeId == 2 
    select new { c.Title, c.ContentId }; 

它應該產生沿着以下的線路查詢(可以使用SQL事件探查器):

select 
     c.Title as Title, 
     c.ContentId as ContentId 
    from Contents c 
    where 
     c.ContentTypeId == 2 

有想到的一些注意事項,但大多數時候EF會產生良好的性能查詢。 要了解更多信息,我推薦以下URL:http://www.sql-server-performance.com/2012/entity-framework-performance-optimization/