2012-12-20 42 views
1
检索数据库值时

我使用Visual Studio 2012和想要做一个SQL查询(使用实体框架5)当我System.ArgumentNullException为:获得异常使用LINQ

堆栈跟踪:

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

MODEL:

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

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

+0

也许你应该向我们展示你想要查询数据库的代码。 –

+0

是的,那肯定会让任何人都更容易帮忙......对不起。 – Niko

回答

2

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

在你的情况下,context.Threadnull,所以FirstOrDefault引发异常如预期。

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

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

    ... 
} 
+0

谢谢你的时间。我知道查询应该找不到任何东西,表格是空的。但是context.Thread = null意味着表本身不存在吗? – Niko

0

这happends如果source为null,你的情况context.Threads由于某种原因空,看MSDN

+0

谢谢你的时间。这是我第一次使用MS SQL - 我认为它包含在Visual Studio中,但是我必须手动安装它吗? – Niko