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
}
內觸及他們這意味着在數據庫中的作曲家有Null值名稱列加載。檢查您的數據庫的Composer名稱,你會看到它。 – DarthVader
@DarthVader:錯了。 – SLaks
這些類名應該是UpperCamelCase而不是複數。 – SLaks