1

当我得到 System.ArgumentNullException 时,我正在使用 Visual Studio 2012 并想做一个 sql 查询(使用实体框架 5):

堆栈跟踪:

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:

询问:

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

我确定我错过了一些明显的东西,但任何帮助将不胜感激。

4

2 回答 2

2

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

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

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

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

    ...
}
于 2012-12-20T13:13:19.533 回答
0

如果源为空,则发生这种情况,在您的情况下 context.Threads 出于某种原因为空,请参阅MSDN

于 2012-12-20T13:16:31.960 回答