对象引用未设置为linq中对象的实例

时间:2012-07-02 02:23:04

标签: c# linq linq-to-sql

我有一些课程,我需要一起使用它们。

样本

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
}

1 个答案:

答案 0 :(得分: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);
}