问题描述
我有这个代码:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!