[英]Why does LINQ to SQL think think that my new object is null when I try to add it to the database?
I am trying to add a record to my database table using LINQ to SQL and ASP.NET MVC 2. 我正在尝试使用LINQ to SQL和ASP.NET MVC 2将记录添加到数据库表中。
The snippet in my controller that populates the LINQ object is this: 我的控制器中填充LINQ对象的代码段是这样的:
/* other code removed */
if (ModelState.IsValid)
{
var stream = new Genesis.Domain.Entities.Stream();
// Handle stream
// Is this stream new?
if (form.StreamID == 0)
{
// create new stream
stream.StreamUrl = form.StreamUrl;
stream.StreamName = form.StreamName;
stream.StreamBody = form.StreamBody;
stream.StreamTitle = form.StreamTitle;
stream.StreamKeywords = form.StreamKeywords;
stream.StreamDescription = form.StreamDescription;
form.StreamID = genesisRepository.CreateStream(stream); // CreateStream() returns ID as long
}
/* other code removed */
The genesisRepository.CreateStream()
looks like this: genesisRepository.CreateStream()
如下所示:
public partial class SqlGenesisRepository : IGenesisRepository
{
public long CreateStream(Stream stream)
{
streamTable.InsertOnSubmit(stream);
streamTable.Context.SubmitChanges();
return stream.StreamID;
}
}
When genesisRepository.CreateStream()
gets executed, I get this error: 执行
genesisRepository.CreateStream()
时,出现以下错误:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 13: public long CreateStream(Stream stream)
Line 14: {
Line 15: streamTable.InsertOnSubmit(stream);
Line 16: streamTable.Context.SubmitChanges();
Line 17: return stream.StreamID;
Source File: C:\path\to\SqlGenesisRepositoryStreamPartial.cs Line: 15
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Data.Linq.Mapping.EntitySetDefSourceAccessor`2.GetValue(T instance) +18
System.Data.Linq.Mapping.MetaAccessor`2.GetBoxedValue(Object instance) +47
System.Data.Linq.StandardTrackedObject.HasDeferredLoader(MetaDataMember deferredMember) +106
System.Data.Linq.StandardTrackedObject.get_HasDeferredLoaders() +107
System.Data.Linq.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary`2 visited, Boolean recurse, Int32 level) +175
System.Data.Linq.StandardChangeTracker.Track(Object obj, Boolean recurse) +83
System.Data.Linq.StandardChangeTracker.Track(Object obj) +12
System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity) +183
Genesis.Domain.Concrete.SqlGenesisRepository.CreateStream(Stream stream) in C:\Documents and Settings\bquakkelaar\Desktop\dropstuff\asp.net mvc\Genesis.0.02\Genesis.Domain\Concrete\SqlGenesisRepositoryStreamPartial.cs:15
Genesis_0_02.Controllers.AdminStreamController.StreamEdit(StreamEditModel form) in C:\Documents and Settings\bquakkelaar\Desktop\dropstuff\asp.net mvc\Genesis.0.02\Genesis.0.02\Controllers\AdminStreamController.cs:107
lambda_method(Closure , ControllerBase , Object[] ) +108
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +127
When I put a breakpoint into the function, I see that stream
is not null. 当我在函数中添加断点时,我看到该
stream
不为空。 Some strings are null. 一些字符串为空。 Required strings are not null (IE: streamName = "name") and StreamID is
0
. 必需的字符串不为null(即:streamName =“ name”),并且StreamID为
0
。
Where am I going wrong? 我要去哪里错了?
I don't think there is a problem with how I instance streamTable
but seeing as how I out of ideas and most people here think that it's null, here is the code that instances streamTable
. 我认为我如何实例化
streamTable
并没有问题,但是我streamTable
想,这里的大多数人都认为它为null,这是实例streamTable
的代码。
public partial class SqlGenesisRepository : IGenesisRepository
{
private Table<Stream> streamTable;
public SqlGenesisRepository(string connectionString)
{
streamTable = (new DataContext(connectionString)).GetTable<Stream>();
}
public IQueryable<Stream> Streams { get { return streamTable; } }
}
And the SqlGenesisRepository is instanced in the controller class like this: SqlGenesisRepository像这样在控制器类中实例化:
public class AdminStreamController : Controller
{
private IGenesisRepository genesisRepository;
public AdminStreamController()
{
//genesisRepository = new FakeGenesisRepository();
genesisRepository = new SqlGenesisRepository(ConfigurationManager.ConnectionStrings["genesis"].ConnectionString);
}
/* rest of code removed for brevity */
}
Thanks to everyone for the attention to this issue. 感谢大家对这个问题的关注。
It looks like the incorrect code wasn't in any of the code I posted here. 看来错误的代码不在我在此处发布的任何代码中。 I rephrased my question and posted it here: Is there a secret to using LINQ to SQL to add records when the object has relationships?
我重新表述了我的问题并将其张贴在这里: 当对象具有关系时,使用LINQ to SQL添加记录是否有秘密? .
。
The solution can be found there! 解决方案可以在这里找到!
Thanks again. 再次感谢。
You don't need to attach the object to the table since the object is new. 由于对象是新对象,因此无需将对象附加到表。 You just need to InsertOnSubmit.
您只需要InsertInSubmit。
If you get a null exception after removing that line, your Stream object is likely missing a required field. 如果删除该行后得到null异常,则您的Stream对象可能缺少必填字段。
Maybe streamTable is null? 也许streamTable为null?
Okay, so based on the stack trace I'm thinking that you may be missing a foreign key constraint. 好的,因此基于堆栈跟踪,我认为您可能缺少外键约束。 What relationships does a
Stream
have? Stream
有什么关系? Can you create a new Stream in your database using hand-coded SQL, given only the information that you have in this code? 仅给出此代码中的信息,您是否可以使用手工编码的SQL在数据库中创建新的Stream?
Have you tried explicitly declaring Stream as Genesis.Domain.Entities.Stream ? 您是否尝试过将Stream明确声明为Genesis.Domain.Entities.Stream?
As in: 如:
private Table<Genesis.Domain.Entities.Stream> streamTable;
public SqlGenesisRepository(string connectionString)
{
streamTable = (new DataContext(connectionString)).GetTable<Genesis.Domain.Entities.Stream>();
}
Because "Stream" alone could be confusing the compiler, as System.IO.Stream
因为单独使用“ Stream”可能会使编译器感到困惑,因为
System.IO.Stream
Also, when you put a breakpoint at 另外,当您在
streamTable.InsertOnSubmit(stream);
...to check if streamTable is null, did you check its contents with the debugger? ...要检查streamTable是否为空,是否用调试器检查了它的内容? That part where it says "Expanding this item will enumerate ...".
它说“扩展此项目将枚举...”的部分。 It's important because generally it lazy loads, therefore it doesn't go to the DB unless it requires a transaction.
这很重要,因为通常它会延迟加载,因此除非需要事务处理,否则它不会进入数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.