0

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
}
8
  • 1
    it means the composer in the database has name column with Null value. check your database for Composer name, you ll see it. Commented Jul 2, 2012 at 2:24
  • Those class names should be UpperCamelCase and not plural. Commented Jul 2, 2012 at 2:27
  • @DarthVader I checked and no problem with member. Member exist with same Guid in comments table. Commented Jul 2, 2012 at 2:30
  • @SLaks not necessarily. he can have his own convention Commented Jul 2, 2012 at 2:33
  • 1
    @DarthVader There are no pointers in .NET, and a null value type (which you describe) is not the same as a null reference. Commented Jul 2, 2012 at 23:27

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.