Ramazan
Ramazan

Reputation: 77

object reference not set to an instance of an object in linq

I have a few classes, I need use them together.

a sample

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;}
}

I try this way

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

when I try get member name from comments it says object reference not set instance of object.

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

SOLUTION I was found solution with get members as list.

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
}

Upvotes: 0

Views: 3671

Answers (1)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28718

LINQ-to-SQL gives lazy-loading by default. You need to force the child objects to load using the DataLoadOptions class.

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();
}

You can also force the child objects to load by touching them within the database context

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);
}

Upvotes: 2

Related Questions