使用Linq检索数据库值时获取异常

时间:2012-12-20 13:04:44

标签: c# .net sql

当我收到System.ArgumentNullException时,我正在使用Visual Studio 2012,并希望进行sql查询(使用实体框架5):

STACK TRACE:

System.ArgumentNullException was unhandled
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: source
  Source=System.Core
  ParamName=source
  StackTrace:
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at Model.RavenDB.ThreadProvider_Raven.Get(Eid item, Rid forum) in c:\Users\fm\Desktop\121219scraper-mssql\Model.RavenDB\ThreadProvider_Raven.cs:line 52
   at Model.RavenDB.ThreadProvider_Raven.Exsist(Eid item, Rid forum, Nullable`1& out_Item) in c:\Users\fm\Desktop\121219scraper-mssql\Model.RavenDB\ThreadProvider_Raven.cs:line 90
   at Scraper.DT_Category.Download() in c:\Users\fm\Desktop\121219scraper-mssql\Scraper\1 (independent)\Download tasks\DT_Category.cs:line 115
   at Scraper.DQ_ParticularForum.QueueReader(Object _this) in c:\Users\fm\Desktop\121219scraper-mssql\Scraper\1 (independent)\DQ_ParticularForum.cs:line 72
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)
  InnerException:

QUERY:

using (var context = new Model.MsSql.Context())
{ 
    var t = context.Threads.FirstOrDefault(s => s.ForumId == (short)forum && s.ExternalId == (int)item);
    ...
}

模特:

namespace Model.MsSql
{
    public class Context : DbContext
    {
        public DbSet<Message> Messages;
        public DbSet<Thread> Threads;
    }

    public class Message
    {
        public int ExternalId;
        public short ForumId;
    }

    public class Thread
    {
        public int ExternalId;
        public short ForumId;
    }
}

我确信我错过了一些显而易见的东西,但任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

扩展方法context.Threads.FirstOrDefault(predicate)实际上是一种简单的static方法:它与Queryable.FirstOrDefault<Thread>(context.Threads, predicate)相同。

在您的情况下,context.Threadnull,因此FirstOrDefault会按预期抛出异常。

您应该在DbSet<>的构造函数中实例化Context属性:

public class Context : DbContext
{
    public Context()
    {
        this.Messages = ...
        this.Threads = ...
    }

    ...
}

答案 1 :(得分:0)

如果source为null,则会发生这种情况,在您的情况下,context.Threads由于某种原因为null,请参阅MSDN