标签: nullreferenceexception

在LINQ to SQL中执行InsertOnSubmit时出现NullReferenceException

在我的数据库中,我有一个名为StaffMembers的表

当我通过linq-to-sql将它带入我的.net项目时,会创建一个实体类StaffMember

现在我还在我的项目中创建了一个部分类StaffMember,以添加我在其他顶层使用的额外属性.例如.IsDeleted属性.此partial类还继承了一个抽象类和接口,以确保还实现了一些其他属性.

现在当我创建一个新的"StaffMember"实例时

例如.StaffMember newStaff = new StaffMember(); 并赋予其所有属性等

然后通过我的Manager调用上下文中的InsertOnSubmit.

Add(StaffMember newStaff)
{
     context.StaffMembers.InsertOnSubmit(newStaff);
     context.Save();
}
Run Code Online (Sandbox Code Playgroud)

我得到一个"对象引用没有设置为对象的实例"错误.

on context.StaffMembers.InsertOnSubmit(newStaff);

堆栈说

"   at System.Data.Linq.Mapping.EntitySetDefSourceAccessor`2.GetValue(T instance)\r\n   at 
System.Data.Linq.Mapping.MetaAccessor`2.GetBoxedValue(Object instance)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.HasDeferredLoader(MetaDataMember deferredMember)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.get_HasDeferredLoaders()\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary`2 visited, Boolean recurse, Int32 level)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(Object obj, Boolean recurse)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(Object obj)\r\n   at System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity)\r\n   at 
BusinessObjects.StaffMemberManager.Add(StaffMember staffMember) in     
C:\\StaffMemberManager.cs:line 251"
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会发生这种情况以及它的方式是什么.

谢谢

c# insertonsubmit nullreferenceexception linq-to-sql

25
推荐指数
1
解决办法
5238
查看次数

检查会话是否为空

我想检查会话是空还是空,即这样的事情:

if(Session["emp_num"] != null)
{

   if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
            {
                //The code
            }
}
Run Code Online (Sandbox Code Playgroud)

要不就

 if(Session["emp_num"] != null)
    {

       // The code
    }
Run Code Online (Sandbox Code Playgroud)

因为有时我只检查:

       if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
                {
                    //The code
                }
Run Code Online (Sandbox Code Playgroud)

我面临以下例外:

空引用异常

c# asp.net session tostring nullreferenceexception

25
推荐指数
4
解决办法
12万
查看次数

App_Web _*.dll中的System.NullReferenceException

我有一个奇怪的问题.

除了一个视图页面,我的MVC应用程序似乎工作得很好.

有问题的视图页面(组织/编辑)在页面上的每个代码项上获得'NullReferenceException'.无论是Html.TextBoxFor()还是HTML.AntiForgeryToken().

我将我的模型,视图和控制器放在另一个我认为相关的问题上 - /sf/ask/1853310651/

如下所示,我的模型内部确实有信息.此屏幕截图是在控制器内部的" 返回视图("编辑",型号) " 处拍摄的.

例外细节

- Source = App_Web_zu4jlld0
- StackTrace =    at ASP._Page_Views_Organization_Edit_vbhtml.Execute() in C:\Users\mtaylor\Projects\Check Im Here\mtaylor-branch\CheckImHere_v2\CheckImHereMVC\Views\Organization\Edit.vbhtml:line 16
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.StartPage.RunPage()
   at System.Web.WebPages.StartPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

视图

@ModelType CheckImHereMVC.OrganizationEditViewModel

@Using Html.BeginForm("Edit", …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc nullreferenceexception razor

25
推荐指数
1
解决办法
3万
查看次数

为什么这个扩展方法在VB.NET中抛出NullReferenceException?

从以前的经验来看,我一直认为在null实例上调用扩展方法是完全合法的(尽管可能不可取).所以在C#中,这段代码编译并运行:

// code in static class
static bool IsNull(this object obj) {
    return obj == null;
}

// code elsewhere
object x = null;
bool exists = !x.IsNull();
Run Code Online (Sandbox Code Playgroud)

但是,我只是为我的开发团队的其他成员组建了一小组示例代码(我们刚刚升级到.NET 3.5,我已经被分配了让团队加快一些新功能的任务我们可以使用),我写了我认为是上面代码的VB.NET等价物,但却发现它实际上抛出了一个NullReferenceException.我写的代码是这样的:

' code in module '
<Extension()> _
Function IsNull(ByVal obj As Object) As Boolean
    Return obj Is Nothing
End Function

' code elsewhere '
Dim exampleObject As Object = Nothing
Dim exists As Boolean = Not exampleObject.IsNull()
Run Code Online (Sandbox Code Playgroud)

调试器就在那里停止,好像我调用了一个实例方法.我做错了什么(例如,我在C#和VB.NET之间定义扩展方法的方式有一些细微差别)吗?在VB.NET中调用null实例上的扩展方法实际上是合法的,尽管它在C#中是合法的吗?(我原以为这是一个.NET的东西,而不是语言特定的东西,但也许我错了.)

任何人都可以向我解释这个吗?

.net vb.net extension-methods nullreferenceexception

23
推荐指数
2
解决办法
2700
查看次数

使用Fragment时,findViewById返回NULL

我是Android开发人员的新手,当然还有Fragments.

我想在main活动中访问我片段的控件,但'findViewById'返回null.没有片段代码工作正常.

这是我的代码的一部分:

片段:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >

    <EditText
        android:id="@+id/txtXML"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:scrollbars="vertical">
    </EditText>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

MainActivity的onCreate:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);

        this.initialisePaging();

        EditText txtXML = (EditText) findViewById(R.id.txtXML);}
Run Code Online (Sandbox Code Playgroud)

在这一点上,txtXML为null.

我的代码中缺少什么或我该怎么办?

android fragment nullreferenceexception android-activity

23
推荐指数
3
解决办法
5万
查看次数

模型中的MVC5 Razor NullReferenceException

出于某种原因,每当我尝试访问我的模型时,我都会收到NullReferenceException.

这是我的控制器的代码:

public async Task<ActionResult> Bar(string fooSlug, int barId)
{
    var foo = await mediaService.GetFoo(fooSlug);
    var bar = await barService.GetBarFromFooByTitleId(foo.TitleId, barId);
    var viewModel = new ViewModels.BarViewModel(foo, bar);
    return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)

ViewModel中的代码:

public class BarViewModel
{
    public Models.Sub.FooDetails Foo{ get; set; }
    public Models.Sub.BarDetails Bar { get; set; }

    public BarViewModel(Models.Sub.FooDetails foo, Models.Sub.BarDetails bar) 
    {
        this.Foo = foo;
        this.Bar = bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的观点:

@model FooBar.ViewModels.BarViewModel

@{
    ViewBag.Title = "Bar";
}

<h2>@Model.Bar.Name</h2>
Run Code Online (Sandbox Code Playgroud)

它继续返回NullReferenceException当我尝试在h2标记内使用它时.我调试了它,.Name属性具有正确的值,但是当我按下继续时它只会抛出错误.

有没有人有这个问题的解决方案?

c# asp.net-mvc nullreferenceexception razor asp.net-mvc-5

23
推荐指数
1
解决办法
1万
查看次数

避免空引用异常

显然,代码中的绝大多数错误都是空引用异常.是否有任何一般技术可以避免遇到空引用错误?

除非我弄错了,否则我知道在F#这样的语言中,不可能有空值.但这不是问题,我问如何避免C#等语言中的空引用错误.

c# exception nullreferenceexception

22
推荐指数
5
解决办法
3万
查看次数

如何分解成员访问表达式链?

短版(TL; DR):

假设我有一个表达式,它只是一个成员访问运算符链:

Expression<Func<Tx, Tbaz>> e = x => x.foo.bar.baz;
Run Code Online (Sandbox Code Playgroud)

您可以将此表达式视为子表达式的组合,每个子表达式包含一个成员访问操作:

Expression<Func<Tx, Tfoo>>   e1 = (Tx x) => x.foo;
Expression<Func<Tfoo, Tbar>> e2 = (Tfoo foo) => foo.bar;
Expression<Func<Tbar, Tbaz>> e3 = (Tbar bar) => bar.baz;
Run Code Online (Sandbox Code Playgroud)

我想要做的是分解e成这些组件子表达式,以便我可以单独使用它们.

更短的版本:

如果我有表达x => x.foo.bar,我已经知道如何中断x => x.foo.如何拉出其他子表达式foo => foo.bar

为什么我这样做:

我试图在C#中模拟"提升"成员访问操作符,就像CoffeeScript的存在访问操作符一样?..Eric Lippert表示,类似的运营商被考虑用于C#,但没有预算来实施它.

如果这样的运算符存在于C#中,您可以执行以下操作:

value = target?.foo?.bar?.baz;
Run Code Online (Sandbox Code Playgroud)

如果target.foo.bar.baz链的任何部分结果为null,那么整个事情将评估为null,从而避免NullReferenceException.

我想要一个Lift可以模拟这种事情的扩展方法:

value = target.Lift(x => x.foo.bar.baz); //returns target.foo.bar.baz or null
Run Code Online (Sandbox Code Playgroud)

我试过的: …

c# lambda expression-trees nullreferenceexception lifting

22
推荐指数
1
解决办法
3650
查看次数

初始化没有"新列表"的列表属性会导致NullReferenceException

using System;
using System.Collections.Generic;

class Parent
{
   public Child Child { get; set; }
}

class Child
{
   public List<string> Strings { get; set; }
}

static class Program
{
   static void Main() {
      // bad object initialization
      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
   }
}
Run Code Online (Sandbox Code Playgroud)

上面的程序编译很好,但在运行时崩溃,而Object引用没有设置为对象的实例.

如果您在上面的代码段中注意到,我在初始化子属性时省略了new.

显然,正确的初始化方法是:

      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { …
Run Code Online (Sandbox Code Playgroud)

c# nullreferenceexception

22
推荐指数
4
解决办法
2078
查看次数

Visual Studio无法打开cshtml文件

我有一个问题,我无法解决.我无法打开Visual Studio c#mvc项目中的每个 cshtml-File(无论我尝试哪个项目).我收到以下错误消息(我试着翻译成英文):

对象引用未设置为对象的实例

谷歌说,它可能是一个NullReferenceExeception.但它与我的代码无关,因为首先我可以成功执行项目,然后在每个项目中发生错误(从今天开始).

c# asp.net-mvc nullreferenceexception visual-studio-2015

21
推荐指数
3
解决办法
9998
查看次数