0

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

一个样品

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

1 回答 1

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);
}
于 2012-07-02T02:31:25.553 回答