2012-08-06 71 views
3

我首先使用實體​​框架代碼,並且我想標記一個集合以供使用不延遲加載。我不知道這個概念被稱爲渴望加載。但到目前爲止,我知道我只需要爲使用延遲加載設置虛擬屬性。但是,如果我不想延遲加載,我應該不要虛擬。默認情況下,如何獲取實體框架ICollection,沒有延遲加載?

public class User 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 

    public ICollection<Role> Roles { get; set; } // no virtual 
} 

public class Role 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<User> Users { get; set; } // virtual 
} 

在我的概念模型中,我總是需要用戶的角色,然後我不想延遲加載。我不想在我的查詢中使用Include()。我只是希望該屬性始終可用。

using (DataContext ctx = new DataContext(connectionString)) 
    { 
     var role = ctx.Roles.Find(1); 
     var users = role.Users; //lazy loading working    

     var user = ctx.Users.Find(1); 

     var roles = user.Roles; //null exception 
    } 

但是,當我加載用戶,實體框架給我的角色屬性爲空。另外,當我加載一個角色時,用戶屬性效果很好,延遲加載。

如果我使用包含,我可以得到它的工作,但我不想使用它。還因爲我不能使用Find方法。

var user = ctx.Users.Include(r => r.Roles).Find(1); //the find method is not accessible 
var user = ctx.Users.Include(r => r.Roles).First(u => Id == 1); //I must use this way 

那麼,我在想錯方法?實體框架在默認情況下假設我們必須使用Include來不使用延遲加載?或者我錯過了一些讓它工作的東西?

+1

可能重複http://stackoverflow.com/questions/5001311/entity-framework-auto-eager-負載)和http://stackoverflow.com/questions/5955544/forcing-eager-loading-for-a-navigation-property – Slauma 2012-08-06 19:29:39

回答

2

你可以加載收集之後還有:

var user = ctx.Users.Find(1); 
    ctx.Entry(user).Collection(u => u.Roles).Load(); 
[實體框架自動負載渴望(的