我有几个课程,我需要一起使用它们。
一个样品
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?
}
解决方案 我找到了将成员作为列表的解决方案。
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
}