LINQ InsertOnSubmit:NullReferenceException

LINQ InsertOnSubmit: NullReferenceException(LINQ InsertOnSubmit:NullReferenceException)
本文介绍了LINQ InsertOnSubmit:NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有这个代码:

using DC = MV6DataContext;
using MV6; // Business Logic Layer
// ...

public DC.MV6DataContext dc = new DC.MV6DataContext(ConnectionString);
IP ip = new IP(Request.UserHostAddress);
dc.IPs.InsertOnSubmit(ip);
dc.SubmitChanges();

// in Business Logic layer:
public class IP : DC.IP {
  public IP(string address) { ... }
}

在尝试 InsertOnSubmit(ip) 时,我收到 NullReferenceException(未将对象引用设置为对象的实例).dc 不为空;ip 和 ip 的所有属性都不为空;虽然有些是空的.

Upon attempting to InsertOnSubmit(ip), I get a NullReferenceException (Object reference not set to an instance of an object). dc is not null; ip and all properties of ip are not null; though some are empty.

VS2008 不允许我进入 InsertOnSubmit,所以我无法知道在评估时具体是什么 null.什么给?

VS2008 won't let me step into InsertOnSubmit, so I have no way of knowing what specifically is null when being evaluated. What gives?

注意:我已经检查过,所有由 FK 关系创建的 Linq.EntitySets 都存在且非空.

Note: I have checked, and all Linq.EntitySets created by FK relationships are present and non-null.

推荐答案

知道了.

我没有创建继承自 DataContext 类的类,而是使用业务逻辑层中的分部类扩展 DC 类本身.从那里我可以添加任何我想要的构造函数和方法.

Rather than creating a class that inherits from the DataContext's class, I extend the DC class itself with a partial class in the Business Logic layer. From there I can add whatever constructors and methods I wish.

在这种情况下,有必要从现有的(自动生成的)构造函数中复制代码:

In this case, it is neccessary to copy the code from the existing (auto-generated) constructor:

public IP(string address) {
Address = address;
Domain = "";
Notes = "";
FirstAccess = DateTime.Now;
LastAccess = DateTime.Now;
this._Sessions = new EntitySet<Session>(new Action<Session>(this.attach_Sessions), new Action<Session>(this.detach_Sessions));
OnCreated(); }

不确定 OnCreated 处理程序中有什么,但它似乎正在做之前让我感到困惑的工作.现在工作正常:)

Not sure what's in that OnCreated handler, but it seems to be doing the work that boned me earlier. Works fine now :)

这篇关于LINQ InsertOnSubmit:NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)