2012-07-02 121 views
0

我有幾個類,我需要將它們一起使用。未將對象引用設置爲linq中對象的實例

樣本

public class members 
{ 
    [Key] 
    public Guid id {get;set;} 
    public string name {get;set;} 
} 

public class comments 
{ 
    [Key] 
    public Guid id {get;set;} 
    public members composer {get;set;} 
    public string comment {get;set;} 
} 

我嘗試這樣

List<comments> listComments = new List<comments>(); 
using(db dc = new db()) 
{ 
    listComments = dc.comment.Where(x => x.id.Equals("an id")).ToList(); 
} 

當我嘗試從評論獲取成員的名字,它說的對象引用未設置對象的實例。

foreach(comments c in listComments) 
{ 
    c.id //no problem 
    c.comment //no problem 
    c.composer.name //error? 
} 

SOLUTION 我發現使用get成員名單的解決方案。

List<comments> listComments = new List<comments>(); 
List<members> lm = new List<members>(); 
using(db dc = new db()) 
{ 
    listComments = dc.comment.Where(x => x.id.Equals("an id")).ToList(); 
    lm = dc.member.ToList(); 
} 




foreach(comments c in listComments) 
{ 
    c.id //no problem 
    c.comment //no problem 
    lm.Where(u => u.id.Equals(c.member.id)).FirstOrDefault().name //that works good 
} 
+1

內觸及他們這意味着在數據庫中的作曲家有Null值名稱列加載。檢查您的數據庫的Composer名稱,你會看到它。 – DarthVader

+1

@DarthVader:錯了。 – SLaks

+0

這些類名應該是UpperCamelCase而不是複數。 – SLaks

回答

2

LINQ-to-SQL默認提供延遲加載。您需要使用DataLoadOptions類強制加載子對象。

List<comments> listComments = new List<comments>(); 
using(db dc = new db()) 
{ 
    var loadOptions = new DataLoadOptions(); 
    loadOptions.LoadWith<comments>(c => c.members); 
    db.LoadOptions = loadOptions; 

    listComments = dc.comment.Where(x => x.id.Equals("an id")).ToList(); 
} 

您還可以強制子對象的數據庫上下文

List<comments> listComments = new List<comments>(); 
using(db dc = new db()) 
{ 
    listComments = dc.comment.Where(x => x.id.Equals("an id")).ToList(); 

    var members = listComments.SelectMany(l => l.members); 
} 
相關問題