简体   繁体   English

LINQ to SQL为什么在尝试将新对象添加到数据库时认为我的新对象为空?

[英]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()时,出现以下错误:

Updated to more accurate error and stacktrace 更新为更准确的错误和堆栈跟踪

    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? 我要去哪里错了?

Edit: How `streamTable` is instanced 编辑:如何`streamTable`被实例化

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?

Edit 编辑

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.

相关问题 当我传递HashSet时,为什么我的泛型类型方法认为T是system.object - Why does my generic type method think T is system.object when I'm passing in a HashSet Why does my code think a value is Microsoft.IdentityModel.Json.Linq.JObject when it is actually supposed to be Newtonsoft.Json.Linq.JObject? - Why does my code think a value is Microsoft.IdentityModel.Json.Linq.JObject when it is actually supposed to be Newtonsoft.Json.Linq.JObject? 我的 C# 程序没有按照我认为的对象初始化顺序初始化对象。 为什么? - My C# program does not initialize the Object how I think it has to according to the Object initialization order. Why? 为什么Resharper认为IPrincipal.Identity永远不会为空? - Why does Resharper think IPrincipal.Identity will never be null? 为什么ReSharper认为MailMessage.From不能为空? - Why does ReSharper think MailMessage.From cannot be null? 为什么Resharper认为私有只读变量可以为null? - Why does resharper think a private readonly variable can be null? 比较字符串为null - 为什么Resharper认为这总是假的? - Compare string to null - Why does Resharper think this is always false? 为什么Visual Studio认为我的“收益回报”方法会返回动态对象? - Why does Visual Studio think my “yield return” method returns a dynamic object? ViewData 以红色突出显示但我认为是我的模型为空? - ViewData highlighted in Red But I think it is my Model that is null? 为什么 Rider 认为我的 controller 方法未被使用? - Why does Rider think my controller methods are unused?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM