tsi*_*ilb 16 c# linq asp.net nullreferenceexception linq-to-sql
我有这个代码:
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) { ... }
}
Run Code Online (Sandbox Code Playgroud)
在尝试InsertOnSubmit(ip)时,我得到一个NullReferenceException(对象引用未设置为对象的实例).dc不为空; ip和ip的所有属性都不为null; 虽然有些是空的.
VS2008不会让我进入InsertOnSubmit,因此在评估时我无法知道具体为null.是什么赋予了?
注意:我已经检查过,并且由FK关系创建的所有Linq.EntitySets都存在且非空.
小智 10
实际上最好添加对构造函数的调用,该构造函数也调用泛型构造函数,例如:
public IP(string address) : this() {
...
}
Run Code Online (Sandbox Code Playgroud)
得到它了.
我没有创建一个继承自DataContext类的类,而是使用业务逻辑层中的部分类扩展DC类本身.从那里我可以添加我想要的任何构造函数和方法.
在这种情况下,有必要从现有(自动生成)构造函数中复制代码:
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(); }
Run Code Online (Sandbox Code Playgroud)
不确定那个OnCreated处理程序中有什么,但它似乎正在做我之前的工作.工作正常:)
由于默认构造函数已初始化base(),this._Sessions并运行OnCreated方法,因此您需要在扩展构造函数中执行以下操作:
public IP(string address) : this()
{
Address = address;
Domain = "";
Notes = "";
FirstAccess = DateTime.Now;
LastAccess = DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)