【问题标题】:object reference not set to an instance of an object in linq对象引用未设置为 linq 中对象的实例
【发布时间】:2012-07-02 02:23:03
【问题描述】:

我有几个类,我需要一起使用。

一个样本

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

当我尝试从 cmets 获取成员名称时,它说对象引用未设置对象实例。

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
}

【问题讨论】:

  • 表示数据库中的作曲家有名称列,值为空。检查您的数据库中的作曲家名称,您会看到它。
  • 那些类名应该是 UpperCamelCase 而不是复数。
  • @DarthVader 我检查了,成员没有问题。 cmets 表中存在具有相同 Guid 的成员。
  • @SLaks 不一定。他可以有自己的约定
  • @DarthVader .NET 中没有指针,并且 null 值类型(您描述的)与 null 引用不同。

标签: c# linq linq-to-sql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多